【问题标题】:How to add multiple lists together, while keeping them as elements in Python?如何将多个列表添加在一起,同时将它们作为 Python 中的元素保存?
【发布时间】:2021-05-02 01:17:25
【问题描述】:

我有大量不同大小的列表,我想将它们合并在一起。我需要能够按顺序检索每个特定的原始列表。例如

list1 = ['apple', 'orange', 'mango']
list2 = ['banana', 'melon']
result: [['apple', 'orange', 'mango'], ['banana', 'melon']]

然后,我需要能够做到:

result[1]
['banana', 'melon']

【问题讨论】:

    标签: python list data-manipulation


    【解决方案1】:

    结果是一个列表,您可以按照您选择的顺序在其中添加列表:

    list1 = ['apple', 'orange', 'mango']
    list2 = ['banana', 'melon']
    
    result = []
    result.append(list1)
    result.append(list2)
    print(result)
    [['apple', 'orange', 'mango'], ['banana', 'melon']]
    

    【讨论】:

      【解决方案2】:

      append function 将为您执行此操作。尝试类似:

      result = []
      result.append(list1)
      result.append(list2)
      # ...
      # append other lists here
      # ...
      
      # this will equal list1
      result[1]
      

      【讨论】:

        【解决方案3】:

        你可以像下面这样非常简单地做到这一点。

        result = [list1, list2]
        

        那么result 将是一个列表列表。

        【讨论】:

          猜你喜欢
          • 2022-07-20
          • 1970-01-01
          • 1970-01-01
          • 2015-03-07
          • 1970-01-01
          • 2020-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多