以下是2个列表
list1 = [[1,2],[3,4]]
list2 = [[11,22],[33,44]]
我尝试过这个
output =list(tuple(zip(i, j)) for i, j in zip(list1, list2))
但是我的输出不符合预期。
[((1, 11), (2, 22)), ((3, 33), (4, 44))]
我想要一一对应如输出之类的
[(1,11),(2,22),(3,33),(4,44)]
我该如何解决这个问题?
您的原始代码会生成一个元组的元组列表,因为您有一个外部
list()
、一个 tuple()
和 zip()
(它生成实际的元组)——您想去掉中间的 tuple()
,相反,只有一个列表理解来捕获 zip(i, j)
生成的所有元组。
您可以通过在推导式中放置两个
for
语句(不将其中任何一个包含在 tuple()
调用中)来完成此操作:
>>> list1 = [[1,2],[3,4]]
>>> list2 = [[11,22],[33,44]]
>>> [z for i, j in zip(list1, list2) for z in zip(i, j)]
[(1, 11), (2, 22), (3, 33), (4, 44)]
你也可以用一个 for 循环来做到这一点:
k=[]
for x,y in enumerate(list1):
k.append(tuple(zip(y,list2[x]))[0])
k.append(tuple(zip(y,list2[x]))[1])
#k
[(1, 11), (2, 22), (3, 33), (4, 44)]
Numpy
尝试这个 numpy 解决方案 -
import numpy as np
np.array(list1+list2).reshape(2,-1).T.tolist()
[[1, 11], [2, 22], [3, 33], [4, 44]]
如果您需要内部列表是元组,请执行此变体。
import numpy as np
list(map(tuple, np.array(list1+list2).reshape(2,-1).T))
[(1, 11), (2, 22), (3, 33), (4, 44)]
#python 程序用于两个嵌套列表的交集 导入迭代工具 导入功能工具
def GCI(lst1, lst2):
temp1 = functools.reduce(lambda a, b: set(a).union(set(b)), lst1)
temp2 = functools.reduce(lambda a, b: set(a).union(set(b)), lst2)
lst3 = [list(set(a).intersection(set(b)))
for a, b in itertools.product(lst1, lst2)
if len(set(a).intersection(set(b))) != 0]
lst3.extend([x] for x in temp1.symmetric_difference(temp2))
return lst3
希望对您有帮助......