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. 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. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.