微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的函数仅适用于列表的第一个元素?

如何解决为什么我的函数仅适用于列表的第一个元素?

我最近才开始学习Python。我想计算列表中每个字符的频率。但是,我的代码仅适用于列表中的第一个元素。

我的代码

import sys

n = [str(s) for s in sys.argv[1].split()]

def countLetter(n):
    frequencyLetter = {}
    for word in n:
        for letter in word:
            keys = frequencyLetter.keys()
            if letter in keys:
                frequencyLetter[letter] += 1
            else:
                frequencyLetter[letter] = 1
    return frequencyLetter

print(countLetter(n))

结果:

C:\Users\john\pythonlearn\testing> main.py hello,there
{'h': 1,'e': 1,'l': 2,'o': 1,',': 1}

应该计算“ hello”和“ there”的字符频率。我不知道为什么输出中有一个---->',':1

解决方法

我在这里看到两个问题:

  1. 您正在错误地解析参数列表。
  2. 无需手动增加计数器。 Counter中的collections类在这里可以很好地工作:
import sys
from collections import Counter

arglist = sys.argv[1:]  # exclude filename

def count_letters(args):
    # Results will be stored in a dict
    res = {}
    for word in args:
        x = Counter(word)
        res.update(x)
    return res

res = count_letters(arglist)
print(res)

此外,鉴于您似乎很想在参数中检查逗号(即使您可以通过用空格将它们分隔开来轻松避免这种情况),也可以在添加它们之前先将其删除到Counter对象:

def count_letters(args):
    # Results will be stored in a dict
    res = {}
    for word in args:
        # If a comma is found,strip it out
        if "," in word:
            word = word.replace(",","")
        x = Counter(word)
        res.update(x)
    return res

使用python parse.py hello therepython parse.py hello,there调用脚本将得到以下相同结果:

{'h': 1,'e': 2,'l': 2,'o': 1,'t': 1,'r': 1}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。