Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据Python中两个不同列表的索引将元素配对来创建新列表?_Python_List - Fatal编程技术网

如何根据Python中两个不同列表的索引将元素配对来创建新列表?

如何根据Python中两个不同列表的索引将元素配对来创建新列表?,python,list,Python,List,例如,我有以下Python列表 A = [1,2,3] B = [4,5,6] 我需要创建一个新的列表C,这样元素就可以根据它们的索引号作为一个单独的列表进行配对。i、 e,C=[[1,4],[2,5],[3,6],[1,4],[2,5],[3,6]] 我已经为此编写了一个代码,但它是纯结构化的。除了下面的代码,你能提供其他更好的方法吗 A = [1,2,3] B = [4,5,6] D = [a,b,c] E = [d,e,f] C = [] list = [] for i in ran

例如,我有以下Python列表

A = [1,2,3]
B = [4,5,6]
我需要创建一个新的列表C,这样元素就可以根据它们的索引号作为一个单独的列表进行配对。i、 e,C=[[1,4],[2,5],[3,6],[1,4],[2,5],[3,6]]

我已经为此编写了一个代码,但它是纯结构化的。除了下面的代码,你能提供其他更好的方法吗

A = [1,2,3]
B = [4,5,6]
D = [a,b,c]
E = [d,e,f]
C = []
list = []


for i in range(len(A)):
    list.append([A[i],B[i]])
C.append(list)
list = []
for i in range(len(D)):
    list.append([D[i],E[i]])
C.append(list)
如果我的代码中有多个类似于上述情况的情况,我必须重复此代码。这在结构上很差。
有人能为这个问题提出更好的解决方法吗?

您可以使用zip,将其转换为列表

这将给出元组列表。如果您想要列表列表,您可以:

[[i,j] for i,j in zip(a,b)]

你可以在一行中尝试类似的东西

C = [[A[i],B[i]] for i in range(len(A))]

但是,如果A和B的长度不相同,请小心

您可以使用zip进行此操作

c= zip(a,b)
c=list(c)
如果你在集合中转换,那么

c=set(c)

您的问题在Python的内置函数中有一个简单的解决方案, “zip”函数接受两个参数iterables并返回一个迭代器。 下面是一个示例代码:

a = [1, 2, 3]
b = [4, 5, 6]
c = list(zip(a, b))
# c -> [(1, 4), (2, 5), (3, 6)]
# if you want the elements to be list instead of tuple you can do
c = [[i, j] for i,j in zip(a, b)]
# c -> [[1, 4], [2, 5], [3, 6]]

使用numpy,以下内容将非常有效

将numpy作为np导入 A=[1,2,3] B=[4,5,6] a=np.arrayA b=np.arrayB c=np.vstack,b.T 打印c C=C.tolist 打印C
小写字母都是numpy数组,大写字母是python数组

谢谢!谢谢你的建议。这很有帮助,很乐意帮忙!请升级我的答案
a = [1, 2, 3]
b = [4, 5, 6]
c = list(zip(a, b))
# c -> [(1, 4), (2, 5), (3, 6)]
# if you want the elements to be list instead of tuple you can do
c = [[i, j] for i,j in zip(a, b)]
# c -> [[1, 4], [2, 5], [3, 6]]