【问题标题】:Convert 2 lists into list of lists将 2 个列表转换为列表列表
【发布时间】:2014-07-18 17:36:52
【问题描述】:

我有 2 个列表:

x = ['a','b','c']
y = ['d','e','f']

我需要一个列表:

z = [['a','d'],['b','e'],['c','f']]

我尝试了什么:

# Concatenate x and y with a space
w = []
for i in range(len(x)):
    w.append(x[i]+" "+y[i])

# Split each concatenated element into a sublist
z = []
for i in range(len(w)):
    z.append(w[i].split())

有没有办法在不使用 2 个 for 循环的情况下直接执行此操作? (我对 Python 很陌生)

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您可以使用zip(如果列表很大,则可以使用itertools.izip):

    >>> x = ['a','b','c']
    >>> y = ['d','e','f']
    >>> zip(x, y)
    [('a', 'd'), ('b', 'e'), ('c', 'f')]
    >>> map(list, zip(x, y))  # If you need lists instead of tuples
    [['a', 'd'], ['b', 'e'], ['c', 'f']]
    >>>
    

    【讨论】:

    • 在 Python 3.x 中,您必须将映射对象转换为列表,如下所示:list(map(list, zip(x, y)))
    【解决方案2】:

    如果两者长度相同,使用enumerate:

    [[a,y[ind]] for ind, a in enumerate(x)]
    

    zip效率更高。

    In [6]: %timeit [[a,y[ind]] for ind,a in enumerate(x)]
    1000000 loops, best of 3: 970 ns per loop
    
    In [7]: %timeit map(list, zip(x, y))
    1000000 loops, best of 3: 1.48 µs per loop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2012-09-29
      • 1970-01-01
      相关资源
      最近更新 更多