列表中有多少特定字符

时间:2016-10-30 19:49:26

标签: python

我有以下问题。在我的代码中,我得到的列表看起来像下面的例子:

['-0---110', '--1--110', '01---100', '1--101-0', '10-1-100',...., '10100010']

现在我想知道字符串出现的频率是0,1,2,3 ......吧。 有一个简单的方法吗?

编辑:我认为像['-0---110', '--1--110', '01---100', '1--101-0', '10-1-100',...., '10100010'].count(-)这样的东西应该有效,但它不是

Edit2:我的第二次尝试似乎也有效:

barcounter = numpy.zeros(8)
for x in range(len(list)):
    rankcounter[8-1-list[x].count("-")] += 1
print("barcounter", barcounter)

2 个答案:

答案 0 :(得分:2)

如果你有Python 2.7+,你实际上可以使用collections.Counter

from collections import Counter

def get_bar_freq(bar_list):
    return Counter(entry.count('-') for entry in bar_list)

在我们的例子中,Counter计算值在迭代中出现的频率。现在要获得一个合适的迭代器,我们只需要获取我们想要计算的任何内容的列表。在这种情况下,字符串包含多少“条形”。

结果将是这样的:

Counter({3: 2, 4: 2, 0: 1, 2: 1})

答案 1 :(得分:1)

我了解你的目标,但你需要遍历列表。这是一个解决方案,它返回一个字典映射,从字符数到字符串中出现的许多条的频率:

from collections import defaultdict

def get_bar_freq(bar_list):
    bar_freq = defaultdict(int)       # a dictionary that will keep track of frequencies 
    for word in bar_list:
        num_bars = word.count('-')
        bar_freq[num_bars] += 1       # increment freq of this many num_bars
    return bar_freq


def main():
    bar_list = ['-0---110', '--1--110', '01---100', '1--101-0', '10-1-100', '10100010']
    print(get_bar_freq(bar_list))

if __name__ == '__main__':
    main()

这输出:defaultdict(<class 'int'>, {0: 1, 2: 1, 3: 2, 4: 2})即表示1个字符串包含0个条形,1个字符串包含2个条形,2个字符串包含3个条形,2个字符串包含4个条形。

在你了解这里发生了什么之后,如果你想看到更多的Pythonic(以及更好的)方式,那么请查看其他答案。您可以使用collections.counter本质上提供此解决方案中bar_freq字典的功能。