【问题标题】:count number of names in list in python [duplicate]计算python列表中名称的数量[重复]
【发布时间】:2018-02-17 11:40:00
【问题描述】:

我有一个列表,里面有名字:

names = ['test','hallo','test']
uniquenames = ['test','hallo']

使用 set 我得到唯一名称,因此唯一名称在不同的列表中

但现在我想计算每个名字有多少个所以测试:2 你好:1

我有这个:

for i in range(len(uniquenames)):
    countname = name.count[i]

但它给了我这个错误: TypeError: 'builtin_function_or_method' 对象不可下标

我该如何解决?

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用字典:

    names = ['test','hallo','test']
    countnames = {}
    for name in names:
        if name in countnames:
            countnames[name] += 1
        else:
            countnames[name] = 1
    
    print(countnames) # => {'test': 2, 'hallo': 1}
    

    如果你想让它不区分大小写,使用这个:

    names = ['test','hallo','test', 'HaLLo', 'tESt']
    countnames = {}
    for name in names:
        name = name.lower() # => to make 'test' and 'Test' and 'TeST'...etc the same
        if name in countnames:
            countnames[name] += 1
        else:
            countnames[name] = 1
    
    print(countnames) # => {'test': 3, 'hallo': 2}
    

    如果您希望键是计数,请使用数组将名称存储在:

    names = ['test','hallo','test','name', 'HaLLo', 'tESt','name', 'Hi', 'hi', 'Name', 'once']
    temp = {}
    for name in names:
        name = name.lower()
        if name in temp:
            temp[name] += 1
        else:
            temp[name] = 1
    countnames = {}
    for key, value in temp.items():
        if value in countnames:
            countnames[value].append(key)
        else:
            countnames[value] = [key]
    print(countnames) # => {3: ['test', 'name'], 2: ['hallo', 'hi'], 1: ['once']}
    

    【讨论】:

    • 谢谢一个问题,我该如何轮换?所以 3 例如成为键,名称成为字典中的索引?
    • @klaashansen 您不能这样做,因为键必须不同,因此如果两个名称具有相同的计数,则只会注册最后一个,但是,有一个使用数组的解决方法,查看更新的答案。
    • 感谢标记为答案
    • @klaashansen 很高兴为您提供帮助 :)。
    【解决方案2】:

    使用来自collectionsCounter

    >>> from collections import Counter
    >>> Counter(names)
    Counter({'test': 2, 'hallo': 1})
    

    此外,为了使您的示例正常工作,您应该将 names.count[i] 更改为 names.count(i),因为 count 是一个函数。

    【讨论】:

      猜你喜欢
      • 2016-03-04
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 2012-09-05
      • 2018-09-04
      相关资源
      最近更新 更多