Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将4个列表合并为1个_Python - Fatal编程技术网

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

如何在python中将4个列表合并为1个,python,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将列表简化为一个列表 >>>

我的代码是

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']
可以使用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 = [line.split() for line in testGraph]
执行:

列表理解,对你有用

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


这应该在对代码进行最小更改的情况下工作。然后,temp将拥有您想要的组合列表

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

这应该在对代码进行最小更改的情况下工作。然后,temp将拥有您想要的组合列表

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

所以制作一个列表,将每个临时值添加到其中。您是想在空白处拆分还是在每个字符处拆分?那么?制作一个列表,将每个临时文件添加到其中。你是想在空白处拆分还是在每个字符处拆分?谁问过要将列表展平?从问题的标题来看,这就是我认为作者要求的。我还添加了另一个选项,即拥有列表列表,而不是将4个列表合并为1谁询问了列表扁平化的问题?从问题的标题来看,这就是我认为作者所要求的。我还添加了另一个选项,即列表列表,并且在迭代文件的行时不将4个列表合并为1。每行都有一个尾随的换行符,因此在您的示例中,testGraph.split“\n”实际上与文件的行为不同。你还需要做一行。strip@IzaakvanDongen但这只是一个例子,在文件中它不需要任何条带,拆分将完美地删除工作,这是第一个代码示例。哦,天哪,我的糟糕。我忘了split是怎么工作的了。对此很抱歉。当您迭代文件的行时,每行都有一个尾随的换行符,因此在您的示例中,testGraph.split“\n”实际上与文件的行为不同。你还需要做一行。strip@IzaakvanDongen但这只是一个例子,在文件中它不需要任何条带,拆分将完美地删除工作,这是第一个代码示例。哦,天哪,我的糟糕。我忘了split是怎么工作的了。很抱歉。