简体   繁体   English

如何在python中从2个数组制作列表?

[英]How to make a list from 2 arrays in python?

I have two arrays, I want to make a list with its first element as [first element of array one, 'first element of array 2'] and so on. 我有两个数组,我要创建一个列表,其第一个元素为[数组1的第一个元素,'数组2的第一个元素'],依此类推。 Basically each elements of a list will be a list. 基本上,列表的每个元素都是一个列表。

lista = [1, 2, 3, 4]
listb = [a, b, c, d]

Desired Output: 所需输出:

listc = [1a, 2b, 3c, 4d]

I believe you're describing what zip does. 我相信您正在描述zip功能。 Also, it seems from the comments that you want the second element to be a string, so here is how: 另外,从注释看来,您希望第二个元素是字符串,因此方法如下:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> [[e1, str(e2)] for e1, e2 in zip(a, b)]
[[1, '4'], [2, '5'], [3, '6']]

You should use zip here. 您应在此处使用zip It functions by iterating over the arguments at the same time. 它通过同时遍历参数来起作用。 You can use it like this: 您可以像这样使用它:

[ [first, str(second)] for first, second in zip(a, b)]

Alternatively, you could do this: 或者,您可以这样做:

list(zip(a, [str(x) for x in b]))

That'll give you a list of tuples rather than a list of lists but if you don't mind the immutability, that might be what you want. 这将为您提供一个元组列表,而不是列表列表,但是如果您不介意不变性,那可能就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM