我有一个如下格式的值列表。对于列表的列表中的每个项目,我试图找出它是否存在于任何其他子列表中-如果存在,我想得到它的计数。
[
['37772'],
['38119', '38120'],
['38103-2807', '38103-2897', '38103', '38104'],
['38138-3904', '38138'],
['37421'],
['37772'],
['37067'],
['37203'],
['38115'],
['38305'],
['37916'],
['37356'],
['38119']
]
结果:
37772 - 2
38119 - 2
38120 - 1
38103-2807 - 1
....
关于如何使用内置函数实现这一点的任何线索?
您可以使用内置模块itertools.chain
和collections.Counter
lst = [['37772'],
['38119', '38120'],
['38103-2807', '38103-2897', '38103', '38104'],
['38138-3904', '38138'],
['37421'],
['37772'],
['37067'],
['37203'],
['38115'],
['38305'],
['37916'],
['37356'],
['38119']]
from itertools import chain
from collections import Counter
items = Counter(chain.from_iterable(lst))
for k, v in items.items():
print(k, v)
>>> 37772 2
>>> 38119 2
>>> 38120 1
>>> 38103-2807 1
>>> ...
li=[
['37772'],
['38119', '38120'],
['38103-2807', '38103-2897', '38103', '38104'],
['38138-3904', '38138'],
['37421'],
['37772'],
['37067'],
['37203'],
['38115'],
['38305'],
['37916'],
['37356'],
['38119']
]
for i in li:
print(str(i)+str(li.count(i)))