【问题标题】:Python append an item in a list to another list and pop the last element in the original onePython将一个列表中的项目附加到另一个列表中并弹出原始列表中的最后一个元素
【发布时间】:2016-11-06 17:01:38
【问题描述】:

我有两个列表,我想将一个列表中的每个元素附加到另一个列表并将结果保存在另一个列表中。这是我的代码,但是当我附加项目并将结果分配给另一个列表时,pop 会从原始列表和结果列表中删除附加的项目。

pi = [['Shirt','Red'],['Shirt','Blue']]
sizes = ['XS','S']
result = []
for item in pi:
    for size in sizes:
        item.append(size)
        result.append(item)
        item.pop(-1) #Once this line is run the size is removed from both result and item

我的最终目标是得到这样的结果列表:

result=[[['Shirt','Red','XS'],['Shirt','Red','S'],['Shirt','Blue','XS'],['Shirt','Blue','S']]]

【问题讨论】:

    标签: python list append


    【解决方案1】:

    如果我没记错的话,问题是引用传递,你必须附加一个列表的副本。

    pi = [['Shirt','Red'],['Shirt','Blue']]
    sizes = ['XS','S']
    result = []
    for item in pi:
        for size in sizes:
            item.append(size)
            result.append(item[:])
            item.pop(-1)
    print(result)
    

    Results of running that code

    【讨论】:

      【解决方案2】:
      pi = [['Shirt','Red'],['Shirt','Blue']]
      sizes = ['XS','S']
      result = []
      for i in pi:
        for j in sizes:
          result.append(i+[j])
      
      print result
      

      应该这样做

      【讨论】:

        【解决方案3】:

        当您将列表添加到结果中时,您需要制作列表的副本,否则对其中一个的修改也会在另一个中发生。

        result.append(list(item))
        

        在这种情况下,您pop 的唯一原因是撤消您刚刚所做的修改,因此最好只对副本执行此操作。

        copy = item[:]
        copy.append(size)
        result.append(copy)
        

        【讨论】:

        • 还有其他更好的方法来解决这个问题吗?正如你所说,我每次都需要撤消修改,实际上我有 3 个列表,每个项目需要相同的算法。
        • @payam 抱歉,我的示例不完整。
        【解决方案4】:

        这是引用问题,使用 copy()

        result.append(item.copy())
        

        【讨论】:

        • 我已经尝试解决这个问题 3 小时了!这很有帮助!谢谢!
        猜你喜欢
        • 1970-01-01
        • 2021-03-17
        • 1970-01-01
        • 2020-10-29
        • 1970-01-01
        • 2017-09-28
        • 1970-01-01
        • 1970-01-01
        • 2016-02-26
        相关资源
        最近更新 更多