[英]Generate a nested list of 0's and 1's by comparing two nested lists in python
我有两个嵌套列表,如下所示:
list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579],
[283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]
list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]
我想比较在上述嵌套列表意思相同的索引位置的元件list_x[0]
应该进行比较list_y[0]
等。
我想生成第三(嵌套)列表,以便对于list_x[0]
每个数字,如果该数字也在list_y[0]
,则生成一个,如果不匹配,则生成零。 应该对list_x[1]
和list_y[1]
执行相同的过程。
我的嵌套输出列表中每个子列表的长度应为10(即,较长子列表的长度,一个为匹配项,一个为零,否则为零)。 所有子列表均按升序排序。
一些额外的信息价值共享是list_y[0]
和list_y[1]
是子集list_x[0]
和list_x[1]
分别。
因此,我要搜索的输出列表如下:
out = [[1,0,0,1,0,1,0,1,1,0], [0,1,1,1,1,1,0,0,0,0]]
我尝试了以下代码,但又得到了10个额外的零
list_x = [y for x in list_x for y in x] #to flatten list_x
result = []
for y in list_y:
sublist = []
for x in list_x:
if x in y:
sublist.append(1)
else:
sublist.append(0)
result.append(sublist)
上面的代码为我提供了以下内容:
result = [[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0]]
谢谢您的帮助!
我们可以使用zip
并发地遍历子列表,然后执行in
check,例如:
[[int(x in suby) for x in subx] for subx, suby in zip(list_x, map(set, list_y))]
然后产生:
>>> [[int(x in suby) for x in subx] for subx, suby in zip(list_x, list_y)]
[[1, 0, 0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0]]
的map(set, list_y)
被用于映射的所有子列表list_y
在套中,由于用于一组通常为O运行的查找(1),而在一个列表中查找需要O(N)。
托马斯,欢迎您!
尝试这个:
#!/usr/bin/env python2
list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579],
[283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]
list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]
answer=[]
for ( index, inner_list ) in enumerate( list_x ):
answer.append([])
for ( inner_index, inner_value ) in enumerate(inner_list):
answer[index].append(0)
if inner_value in list_y[ index ]:
answer[index][inner_index] = 1
print answer
试试看...您将获得输出
list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579],
[283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]
list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]
result =[]
for ind,lst in enumerate(list_x):
sublist =[]
for ele in lst:
if ele in list_y[ind]:
sublist .append(1)
else:
sublist .append(0)
result.append(sublist )
print(result)
产量
[[1,0,0,1,0,1,0,1,1,0], [0,1,1,1,1,1,0,0,0,0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.