x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']]
假设我们有一个包含随机 str 字母的列表。 我如何创建一个函数,以便它告诉我字母“a”出现了多少次,在本例中为 2。或任何其他字母,如“b”出现一次,“f”出现两次。 ETC。 谢谢!
请您参考如下方法:
您可以展平列表并使用 collections.Counter:
>>> import collections
>>> x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']]
>>> d = collections.Counter(e for sublist in x for e in sublist)
>>> d
Counter({'a': 2, 'c': 2, 'f': 2, 'b': 1, 'e': 1, 'd': 1})
>>> d['a']
2
