python - 如何在python中将4个列表合并为1个

标签 python

我的代码是这样的

testGraph=open(input("Enter a file name:"))
for line in testGraph:
  temp=line.split()

输出就像

['0', '1']
['2', '1']
['0', '2']
['1', '3']

我想把它们变成

[['0', '1'],['2', '1'],['0', '2'],['1', '3']]

有人可以帮我吗?

最佳答案

您可以使用 itertools.chain() 将列表扁平化为一个列表。

>>> cmd = ['ls', '/tmp']
>>> numbers = range(3)
>>> itertools.chain(cmd, numbers, ['foo', 'bar'])
<itertools.chain object at 0x0000000003943F28>
>>> list(itertools.chain(cmd, numbers, ['foo', 'bar']))
['ls', '/tmp', 0, 1, 2, 'foo', 'bar']

但是如果你想要一个列表的列表,那么附加到列表将是你的选择。

testGraph=open(input("Enter a file name:"))
result = []
for line in testGraph:
  result.append(line.split())

关于python - 如何在python中将4个列表合并为1个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45785079/

相关文章:

python - 使用 numpy.memmap 映射设备文件

Python Pandas 数据帧移位在应用函数中不起作用

python - 函数调用中的星号和双星号运算符是什么意思?

python请求很慢

python - 如何在不保存的情况下使用 PIL 更改图像的 DPI?

python - 无法在 Keras 中使用 VGG19 预测单个图像的标签

Python键入TypeVar(A,B,covariant = True)是什么意思?

python - 正则表达式按数字匹配组

python - 使用 python 下载大 zip 文件

python - 将当前类作为返回类型注释