我有两个嵌套列表,如下所示:
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]
中,则生成一个 1,如果没有匹配,则生成一个零。 list_x[1]
和 list_y[1]
也应执行相同的过程。
嵌套输出列表中每个子列表的长度应为 10(即较长子列表的长度,如果有匹配则为 1,如果没有匹配则为 0)。所有子列表均按升序排序。
值得分享的一些附加信息是
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
检查,例如:
[[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)。
托马斯,欢迎来到SO!
试试这个:
#!/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]]
由于 y 列表是子集并且很小,因此您只需计算 x 值在其中出现的频率即可:
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]]
expect = [[1,0,0,1,0,1,0,1,1,0], [0,1,1,1,1,1,0,0,0,0]]
result = [
[*map(y.count, x)]
for x, y in zip(list_x, list_y)
]
print(result == expect)