[英]How to merge 4 lists into 1 in python
my code is like 我的代码就像
testGraph=open(input("Enter a file name:"))
for line in testGraph:
temp=line.split()
and the out put is like 而输出就像
['0', '1']
['2', '1']
['0', '2']
['1', '3']
and I want to make them into 我想让他们成为
[['0', '1'],['2', '1'],['0', '2'],['1', '3']]
could someone help me? 有人可以帮我吗?
You can use itertools.chain()
to flat lists into one list. 您可以使用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']
But if you want to have a list of lists, then appending to the list would be your choice. 但是,如果您想拥有列表列表,则可以选择将列表追加到列表中。
testGraph=open(input("Enter a file name:"))
result = []
for line in testGraph:
result.append(line.split())
List comprehension
, works for you, List comprehension
,为您服务,
testGraph = open(input("Enter a file name:"))
result = [line.split() for line in testGraph]
Execution: 执行:
In [29]: testGraph = open('abc.txt')
In [30]: [line.split() for line in testGraph]
Out[30]: [['0', '1'], ['2', '1'], ['0', '2'], ['1', '3']]
This should work with minimal change to your code. 这应该可以对您的代码进行最小的更改。 temp
will then have the combined list you want. temp
将具有您想要的合并列表。
testGraph=open(input("Enter a file name:"))
temp = []
for line in testGraph:
temp.append(line.split())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.