我有两个列表,我需要使用第一个列表的第一个元素来遍历第二个列表中的所有元素。然后我需要从第一个列表中拾取第二个元素,并遍历第二个列表中的所有元素,然后是第三个元素...
l1 = [25,45,33]
l2 = [70,25,45,25,25,45,25,60]
outp = []
counter = 0
def my_func():
for x, x2 in enumerate(l2):
if x1 == l1[counter]:
outp.append(x)
return outp
counter = counter +1
else:
x1 != l1[counter]:
outp.append([])
OUT = my_func()
“在我的示例中,我需要最终的重新存储在子列表中:”
“ [0]:[1,3,4,6]”
“ [1]:[2,4]”
“ [2]:[]”
答案 0 :(得分:2)
这是一种结合字典理解和列表理解的方法:
{x : [i for i, z in enumerate(l2) if z == y] for x, y in zip(range(0, len(l1)), l1)}
输出:
{0: [1, 3, 4, 6], 1: [2, 5], 2: []}
答案 1 :(得分:1)
您可以遍历第一个列表并使用列表推导来生成索引。
def x_in_y(x, y):
out = []
for xx in x:
out.append([i for i, yy in enumerate(y) if yy == xx])
return out
l1 = [25,45,33]
l2 = [70,25,45,25,25,45,25,60]
x_in_y(l1, l2)
# returns:
[[1, 3, 4, 6], [2, 5], []]
答案 2 :(得分:0)
l1 = [25, 45, 33]
l2 = [70, 25, 45, 25, 25, 45, 25, 60]
outp = []
def match_elems(l1, l2):
for i, l1_elm in enumerate(l1):
match_list = []
for j, l2_elm in enumerate(l2):
if l2_elm == l1_elm:
match_list.append(j)
outp.append(match_list)
return outp
print(match_elems(l1, l2))
# Returns:
[[1, 3, 4, 6], [2, 5], []]