如何使用列表理解将二维列表中的值匹配到另一个二维列表?
How to you use list comprehension to match values from a two dimensional list to another two dimensional list?
例如我有两个列表,它们是二维列表
a=[[7,9,10,11,12],[4,11,14,16,21]]
b=[[5,9,14,15],[7,12,15,17,19],[8,14,15,17,19],[13,15,17,20,22]]
我希望结果是
0. [[9],[12,7]]
1. [[4], [14]]
从您的评论中复制:
for 循环。
for idx,item_a in enumerate(a):
result = []
for item_b in b:
result.append(list(set(item_a) & set(item_b)))
print(idx,result))
如果我正确理解你的问题,此代码适合你
res = list(enumerate([[list(set(x) & set(y)) for x in b] for y in a]))
# output: [(0, [[9], [12, 7], [], []]), (1, [[14], [], [14], []])]
如您所见,res
是一个元组列表,例如:(idx, list_value)
。
例如 res[0]
包含元组 (0, [[9], [12, 7], [], []])
,其中 0
是索引,[[9], [12, 7], [], []]
是相应值列表的列表。为了消除所有疑问,这是代码:
idx0, lst0 = res[0] # or equivalently idx0, lst0 = res[0][0], res[0][1]
print('idx of res[0] is %d and the corresponding list is: %s' %(idx0, str(lst0)))
# output: idx of res[0] is 0 and the corresponding list is: [[9], [12, 7], [], []]
你可以这样打印所有的结果:
for idx, val in res:
print(idx, val)
你会得到:
0 [[9], [12, 7], [], []]
1 [[14], [], [14], []]
例如我有两个列表,它们是二维列表
a=[[7,9,10,11,12],[4,11,14,16,21]]
b=[[5,9,14,15],[7,12,15,17,19],[8,14,15,17,19],[13,15,17,20,22]]
我希望结果是
0. [[9],[12,7]]
1. [[4], [14]]
从您的评论中复制:
for 循环。
for idx,item_a in enumerate(a):
result = []
for item_b in b:
result.append(list(set(item_a) & set(item_b)))
print(idx,result))
如果我正确理解你的问题,此代码适合你
res = list(enumerate([[list(set(x) & set(y)) for x in b] for y in a]))
# output: [(0, [[9], [12, 7], [], []]), (1, [[14], [], [14], []])]
如您所见,res
是一个元组列表,例如:(idx, list_value)
。
例如 res[0]
包含元组 (0, [[9], [12, 7], [], []])
,其中 0
是索引,[[9], [12, 7], [], []]
是相应值列表的列表。为了消除所有疑问,这是代码:
idx0, lst0 = res[0] # or equivalently idx0, lst0 = res[0][0], res[0][1]
print('idx of res[0] is %d and the corresponding list is: %s' %(idx0, str(lst0)))
# output: idx of res[0] is 0 and the corresponding list is: [[9], [12, 7], [], []]
你可以这样打印所有的结果:
for idx, val in res:
print(idx, val)
你会得到:
0 [[9], [12, 7], [], []]
1 [[14], [], [14], []]