将 2 个列表转换为列表列表 [英] Convert 2 lists into list of lists

查看:46
本文介绍了将 2 个列表转换为列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个列表:

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

我需要一个列表:

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

我尝试了什么:

# 用空格连接 x 和 yw = []对于范围内的 i(len(x)):w.append(x[i]+" "+y[i])# 将每个连接的元素拆分为一个子列表z = []对于范围内的 i(len(w)):z.append(w[i].split())

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

解决方案

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

<预><代码>>>>x = ['a','b','c']>>>y = ['d','e','f']>>>拉链(x,y)[('a', 'd'), ('b', 'e'), ('c', 'f')]>>>map(list, zip(x, y)) # 如果你需要列表而不是元组[['a', 'd'], ['b', 'e'], ['c', 'f']]>>>

I have 2 lists :

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

I need a single list of lists :

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

What I tried :

# 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())

Is there a way to do this directly without using 2 for loops ? (I am very new to Python)

解决方案

You can use zip (itertools.izip if the lists are large):

>>> 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']]
>>>

这篇关于将 2 个列表转换为列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆