我的代码是这样的
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/