[英]Find the lists that share common values
我的问题与以下主题密切相关。 我有许多列表,我想找到具有共同价值的列表。 所有列表的大小相同。 列表的总数是可变的并且可以增加。 最少列表数为2
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]
预期的 output 为:
[a, c]
理想情况下,我也想要最快的方法。 提前致谢,
您可以将它们转换为集合并使用intersection() function,如果它确实返回一个值,则有一些共同的值
lists = []
for i in a:
if i in b:
lists.append([a, b])
if i in c:
lists.append([a, c])
for i in b:
if i in c:
lists.append([b, c])
print(lists)
要简单地检查两个列表是否共享至少一个值,您可以使用...
a = [1, 2, 3, 4]
b = [9, 10, 11, 1]
if any(a) == any(b):
print(True)
如果您想要 n 个命名列表的['a', 'c']
output ,您可以将它们保存在dict
中并使用any
在循环它们时检查它们是否相交:
lists = {
"a" : [1, 2, 3, 4],
"b" : [5, 6, 7, 8],
"c" : [9, 10, 11, 1]
}
res = []
for l in lists:
for l2 in lists:
if l is not l2:
if any(i in lists[l] for i in lists[l2]):
res.append(l)
break;
print(res)
OUT: ['a', 'c']
利用我对 Python 列表的有限知识,我想出了这个:
class countedList:
def __init__(self,listt):
self.listt = listt
self.sharedNum = 0
def mostCommon(*lists):
for item in lists:
for listItem in item.listt:
for item2 in lists:
item2.sharedNum+=item2.listt.count(listItem)
new = sorted(lists,key=lambda clist: clist.sharedNum,reverse=True)
return new[:2]
test = mostCommon(countedList([1, 2, 3, 4]),countedList([5, 6, 7, 8]),countedList([9, 10, 11, 1]))
嗯,是的,我必须为它制作一个定制的 class。 在测试运行中它给出了:
>>> test[0].listt
[1, 2, 3, 4]
>>> test[1].listt
[9, 10, 11, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.