【问题标题】:Creating a unique list with the each subsequent item from a series of lists使用一系列列表中的每个后续项目创建一个唯一列表
【发布时间】:2018-10-10 00:27:55
【问题描述】:

如何创建一个新列表,结合旧列表的第一个值,然后是第二个值等。

list_1 = [1,2,3,4]
list_2 = [1,2,3,4]
list_3 = [1,2,3,4]
new_list = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]]

【问题讨论】:

    标签: python list for-loop


    【解决方案1】:

    纯蟒蛇:

    你可以使用zip:

    new_list = list(map(list, zip(list_1,list_2,list_3)))
    
    >>> new_list
    [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]
    

    替代方案:

    numpy:

    import numpy as np
    new_list = np.array([list_1,list_2,list_3]).T.tolist()
    
    >>> new_list
    [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]
    

    【讨论】:

      【解决方案2】:

      这是使用列表推导的另一种方法。

      new_list = [list(args) for args in zip(list_1, list_2, list_3)]
      

      【讨论】:

        【解决方案3】:

        如果我们enumerate 一个列表中的索引从该列表到所有 3

        new_list = [[list_1[i], list_2[i], list_3[i]] for i, _ in enumerate(list_1)]
        # [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]
        

        【讨论】:

          猜你喜欢
          • 2016-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-15
          相关资源
          最近更新 更多