假设我的输入是列表的列表:
[[1, 2], [3, 6], [1, 4], [3, 8]]
我需要在输出中获得匹配项,但不是全部在一个列表中。例如,1位于列表[1, 2]
中,也位于列表[1, 4]
中。我想要得到[1, 2, 4]
和相同的3。
(1, 2, 4)
(3, 6, 8)
有可能吗?
使用list_of_list
的解决方案lists = [[1, 2], [3, 6], [1, 4], [3, 8]]
indx = [0]*len(lists)
final=[]
for i in lists:
temp =[]
for k in range(len(lists)):
if i[0] in lists[k] and indx[k]==0:
indx[k] = 1
temp+=lists[k]
if len(temp)>0:
final.append(set(temp))
print(final)
上述代码的输出将是[{1, 2, 4}, {8, 3, 6}]
- 我创建了一个列表,跟踪已经使用的元素
- 那么我检查列表中每个元素的第0个索引,如果它还没有被检查
samples = [[1,2], [1,4], [3,6], [3,8]]
key = 3
list(set([l for j in [i for i in samples if key in i] for l in j]))
# [8, 3, 6]
[i for i in samples if key in i]
创建候选列表。剩下的是列表的平坦化,使用list(set(...))
,您实现了示例是唯一的。
使用列表推导式返回包含您正在查找的任何项的列表的列表。然后连接(我在这里找到了sum方法)这些列表并创建一个集合
def get_matches(matches, alist):
return set(sum([y for x in matches for y in alist if(x in y)], []))
get_matches([1,4], [[1,2], [1,4], [3,6], [3,8]])
get_matches([3], [[1,2], [1,4], [3,6], [3,8]])