【发布时间】:2020-05-31 18:25:47
【问题描述】:
我的问题与以下topic 密切相关。
我有许多列表,我想找到具有共同价值的列表。所有列表的大小相同。列表的总数是可变的并且可以增加。最少列表数为2
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]
预期的输出是:
[a, c]
理想情况下,我也想要最快的方法。提前致谢,
【问题讨论】:
我的问题与以下topic 密切相关。
我有许多列表,我想找到具有共同价值的列表。所有列表的大小相同。列表的总数是可变的并且可以增加。最少列表数为2
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]
预期的输出是:
[a, c]
理想情况下,我也想要最快的方法。提前致谢,
【问题讨论】:
您可以将它们转换为集合并使用intersection() 函数,如果它确实返回一个值,则有一些共同的值
【讨论】:
如果您想要 n 个命名列表的 ['a', 'c'] 输出,您可以将它们保存在 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']
【讨论】:
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)
【讨论】:
利用我对 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]))
嗯,是的,我必须为它编写一个自定义类。在测试运行中它给出了:
>>> test[0].listt
[1, 2, 3, 4]
>>> test[1].listt
[9, 10, 11, 1]
【讨论】:
简单地检查两个列表是否共享至少一个您可以使用的值...
a = [1, 2, 3, 4]
b = [9, 10, 11, 1]
if any(a) == any(b):
print(True)
【讨论】: