Is there a way to merge multiple list index by index?

前端 未结 4 1875
粉色の甜心
粉色の甜心 2021-01-03 07:18

For example, I have three lists (of the same length)

A = [1,2,3]
B = [a,b,c]
C = [x,y,z]

and i want to merge it into something like: [[1,a,

4条回答
  •  别那么骄傲
    2021-01-03 08:06

    It looks like your code is meant to say answer = [], and leaving that out will cause problems. But the major problem you have is this:

    answer = answer.extend(temp)
    

    extend modifies answer and returns None. Leave this as just answer.extend(temp) and it will work. You likely also want to use the append method rather than extend - append puts one object (the list temp) at the end of answer, while extend appends each item of temp individually, ultimately giving the flattened version of what you're after: [1, 'a', 'x', 2, 'b', 'y', 3, 'c', 'z'].

    But, rather than reinventing the wheel, this is exactly what the builtin zip is for:

    >>> A = [1,2,3]
    >>> B = ['a', 'b', 'c']
    >>> C = ['x', 'y', 'z']
    >>> list(zip(A, B, C))
    [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]
    

    Note that in Python 2, zip returns a list of tuples; in Python 3, it returns a lazy iterator (ie, it builds the tuples as they're requested, rather than precomputing them). If you want the Python 2 behaviour in Python 3, you pass it through list as I've done above. If you want the Python 3 behaviour in Python 2, use the function izip from itertools.

提交回复
热议问题