简体   繁体   中英

How do I convert 3 Lists in a combined array of 3 members in Python?

I'm a noob in Python 3, I'm coming from Java and javascript.

How can I go from

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = ['red', 'green', 'blue']

to

x = [ ['a', 1, 'red'], ['b', 2, 'green'], ['c', 3, 'blue'] ] 

in an easy way, without using some loop (while/for/map) ?

Thanks

This is what the zip builtin was made for. zip takes an arbitrary number of iterables and returns tuples with items from corresponding indices.

>>> a = ['a', 'b', 'c']
>>> b = [1, 2, 3]
>>> c = ['red', 'green', 'blue']
>>> list(map(list, zip(a, b, c)))
[['a', 1, 'red'], ['b', 2, 'green'], ['c', 3, 'blue']]

The tuples zip generates are explicitly converted to lists here because you requested lists. If there's no particular reason for having lists instead of tuples, just use

>>> list(zip(a, b, c))
[('a', 1, 'red'), ('b', 2, 'green'), ('c', 3, 'blue')]

Assuming all lists have the same length, you can use list comprehension

x = [[a[i],b[i],c[i]] for i in range(len(a)) ]

this will result in

[['a', 1, 'red'], ['b', 2, 'green'], ['c', 3, 'blue']]

def combine_list(*args):
     return map(list, args)

final = list(combine_list(a,b,c))

It will be like:

[['a', 'b', 'c'], [1, 2, 3], ['red', 'green', 'blue']]

As you mentioned "in an easy way, without using some loop (while/for/map)"

This was the easiest approach I could think of:

Firstly, define a, b, c that contains data, p, q, r as temporary list and an empty list x to store final output. Simple use append function of list sequentially to append a, b and c to x. Print x and you will have a list of lists without using any for-loop! But at the stake of extra memory and duck typing.

    a = ['a', 'b', 'c']
    b = [1, 2, 3]
    c = ['red', 'green', 'blue']

    p = []
    q = []
    r = []

    x = []

    p.append(a[0])
    p.append(b[0])
    p.append(c[0])

    q.append(a[1])
    q.append(b[1])
    q.append(c[1])

    r.append(a[2])
    r.append(b[2])
    r.append(c[2])

    x.append(p)
    x.append(q)
    x.append(r)

    print(x)

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.

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