[英]two nested list make one list
Here are 2 list below以下是 2 个列表
list1 = [[1,2],[3,4]]
list2 = [[11,22],[33,44]]
I tried to this我试过这个
output =list(tuple(zip(i, j)) for i, j in zip(list1, list2))
But my output is not as desired.但是我的 output 并不如人意。
[((1, 11), (2, 22)), ((3, 33), (4, 44))]
I want to one to one correspondence such as output like我要一一对应比如output之类的
[(1,11),(2,22),(3,33),(4,44)]
how can I fix this?我怎样才能解决这个问题?
Your original code generates a list of tuples of tuples because you have an outer list()
, a tuple()
, and zip()
which generates the actual tuples -- you want to get rid of that tuple()
in the middle and instead just have a single list comprehension that captures all the tuples produced by zip(i, j)
.您的原始代码生成元组的元组列表,因为您有一个外部
list()
,一个tuple()
和zip()
生成实际的元组 - 您想要摆脱中间的那个tuple()
而是只需要一个列表理解来捕获zip(i, j)
生成的所有元组。
You can do this by putting two for
statements in the comprehension (not wrapping either in a tuple()
call):您可以通过在理解中放置两个
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)]
you can do like this as well with one for loop:您也可以使用一个 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
Try this numpy solution -试试这个 numpy 解决方案 -
import numpy as np
np.array(list1+list2).reshape(2,-1).T.tolist()
[[1, 11], [2, 22], [3, 33], [4, 44]]
If you need the internal lists to be tuples, do this variation.如果您需要内部列表是元组,请执行此变体。
import numpy as np
list(map(tuple, np.array(list1+list2).reshape(2,-1).T))
[(1, 11), (2, 22), (3, 33), (4, 44)]
#python program for intersection of two nested lists import itertools import functools #python 求两个嵌套列表交集的程序 import itertools import functools
def GCI(lst1, lst2): 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
Hope it helps.....希望能帮助到你.....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.