有没有办法按索引合并多个列表索引? [英] Is there a way to merge multiple list index by index?

查看:252
本文介绍了有没有办法按索引合并多个列表索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有三个(相同长度)列表

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

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

我希望将它合并为:
[[1,a,x],[2,b,y],[3,c,z]]。

and i want to merge it into something like: [[1,a,x],[2,b,y],[3,c,z]].

以下是我目前的情况:

define merger(A,B,C):
  answer = 
  for y in range (len(A)):
    a = A[y]
    b = B[y]
    c = C[y]
    temp = [a,b,c]
    answer = answer.extend(temp)
  return answer

收到错误:

'NoneType'对象没有属性'extend'

'NoneType' object has no attribute 'extend'

推荐答案

看起来您的代码应该说 answer = [] ,而将其删除会导致问题。但你遇到的主要问题是:

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 修改回答 并返回None。将其保留为 answer.extend(temp),它将起作用。您可能还想使用追加方法而不是 extend - 追加puts 一个对象 (列表 temp )在 answer 结尾处,而 extend 单独追加每个项目的temp,最终给出你所追求的扁平化版本: [1,'a','x',2,'b' ,'y',3,'c','z']

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'].

但是,不是重新发明轮子,这正是内置的 zip 适用于:

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')]

请注意,在Python 2中, zip 返回元组列表;在Python 3中,它返回一个惰性迭代器(即,它根据请求构建元组,而不是预先计算它们)。如果你想要Python 3中的Python 2行为,你将通过 list 传递它,就像我上面所做的那样。如果您想要Python 2中的Python 3行为,请使用 <$ c来自itertools的$ c> izip

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.

这篇关于有没有办法按索引合并多个列表索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆