gpt4 book ai didi

python - 如何从列表列表中获取最小的重复项列表?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:11:45 25 4
gpt4 key购买 nike

我是一名 Python 新手,我使用 list 工作了 2 个月,我有一些问题。我有一些 list ,他们有重复的项目。我可以在 2 个列表之间获取重复项,现在我希望列表的数量和深度像这个例子一样增加: http://i219.photobucket.com/albums/cc213/DoSvn/example.png .我想从红色部分获取重复项的父级,而不是蓝色部分或这些重复项的列表。我该怎么做 ?谢谢:)


更新:感谢您的回答 :D 我用过 Set,它很棒。但我想如果我不知道列表列表的大小,仅此而已,它们是动态列表,我可以像那个例子一样得到所有的红色部分吗:http://i219.photobucket.com/albums/cc213/DoSvn/example02.png

最佳答案

如果您正在搜索这样的内容:http://i219.photobucket.com/albums/cc213/DoSvn/example02.png

然后您可以试试计数器(在 Python 2.7+ 中可用)。它应该像这样工作:

from collections import Counter

c = Counter()
for s in (listOfLists):
c.update(s)

for item, nbItems in c.iteritems():
if nbItems == 3:
print '%s belongs to three lists.' % item

或使用较旧的 Python:

counter = {}

for s in (listOfLists):
for elem in s:
counter[elem] = counter.get(elem, 0) + 1

for item, nbItems in counter.iteritems():
if nbItems == 3:
print '%s belongs to three lists.' % item

关于python - 如何从列表列表中获取最小的重复项列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4011967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com