【问题标题】:Is there a way to merge multiple list index by index?有没有办法按索引合并多个列表索引?
【发布时间】:2014-05-01 03:13:54
【问题描述】:

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

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

我想把它合并成类似的东西: [[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”对象没有“扩展”属性

【问题讨论】:

  • 直接回答你的问题 answer = [] not answer = 虽然我很惊讶你没有收到语法错误但可能被你的函数吞噬了?还可以扩展工作,因此您需要执行 answer.extend(something) not answer = answer.extend()

标签: python list indexing


【解决方案1】:

看起来您的代码是要说answer = [],而忽略它会导致问题。但是您遇到的主要问题是:

answer = answer.extend(temp)

extend 修改answer并返回None。将其保留为 answer.extend(temp) 即可。您可能还想使用append 方法而不是extend - 在answer 的末尾追加放置一个对象(列表temp),而extend 追加temp 的每个项目,最终给出你所追求的扁平化版本:[1, 'a', 'x', 2, 'b', 'y', 3, 'c', 'z']

但是,与其重新发明轮子,这正是内置 zip 的用途:

>>> 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 行为,请使用来自 itertools 的函数 izip

【讨论】:

  • 对不起,我错了,需要追加而不是扩展,您的解决方案仍然不存在,因为您有一个元组列表
  • 啊,对extend函数不熟悉。我现在明白错误了,谢谢!
【解决方案2】:

要获得列表列表,您可以使用内置函数zip()列表推导zip() 结果的每个元素从tuplelist

A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]

X = [list(e) for e in zip(A, B, C,)]

print X
>>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

【讨论】:

    【解决方案3】:

    假设您是在课堂上这样做,而不是学习使 Python 成为出色工具的所有技巧,这就是您所需要的。你有两个问题,首先如果你想扩展,那么你就在原地做,但你想要的结果表明你想追加,而不是扩展

    def 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.append(temp)
       return answer
    
    
    >>> answer
    [[1, 'a', 'x'], [2, 'b', 'y'], [3, 'c', 'z']]
    

    【讨论】:

      【解决方案4】:

      我只是想知道同样的事情。我是一个使用代码学院的菜鸟。这就是我想在索引处结合两个列表索引

      toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies',    'mushrooms']
      
      prices = [2,6,1,3,2,7,2]
      
      num_pizzas = len(toppings)
      
      print("We sell "+str(num_pizzas)+" different kinds of pizza!")
      
      ***pizzas = list(zip(toppings, prices))***
      
      print (pizzas)
      

      打印出来的披萨列表...[('pepperoni', 2), ('pineapple', 6), ('cheese', 1), ('sausage', 3), ('olives', 2 ), ('凤尾鱼', 7), ('蘑菇', 2)]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-27
        • 2012-05-31
        • 2019-10-04
        • 1970-01-01
        相关资源
        最近更新 更多