我正在编写个人代码来为研究分析做一些事情。 我有一个包含 14 个列表的列表列表,我想找到至少 10 个列表之间共享的元素。到目前为止,这是我在所有列表中找到共享元素的方法。我还写了一个如果某个元素出现超过 10 次则输出,这对我的目的不起作用,因为列表列表中的某些列表具有相同值的倍数。下面是我的示例代码。
def find_duplicates(master_list):
result = set(master_list[0])
for organism in master_list[1:]:
result.intersection_update(organism)
x = list(result)
with open("duplicates.txt", "wt") as t:
for a in x:
t.write(a + "\n")
版本二
def find_duplicates(master):
new = []
for organism in master:
for feature in organism:
if sum(organism.count(feature) for organism in master) == 10:
if y not in new:
new.append(y)
with open("duplicates_list.txt", "wt") as t:
for a in new:
t.write(a + "\n")
有没有人对我如何修改它以查找列表列表中至少 10 个列表中的元素有任何建议。
请您参考如下方法:
如果顺序无关紧要,您可以使用 Counter dict 进行计数,在每个子列表上调用 set 以获得唯一值:
from collections import Counter
def find_duplicates(master):
cn = Counter(feature for organism in master for feature in set(organism))
with open("duplicates_list.txt", "wt") as t:
for k,v in cn.items():
if v >= 10:
t.write("{}\n".format(k))
对于 v 即计数至少为 10 将至少有 10 个具有特定特征的子列表作为 set(organism) 确保即使出现特征不止一次我们只看到一次,因为我们的集合不能有重复项。
