python 中的拉链循环
loop of zips in python
我想创建一个 zip 循环 我有 sample.csv
文件,其中包含以下条目:
> 1 2 3 4
> a b c d
> apple banana cat dog
并具有以下代码:
sample= open("sample.csv)
lines = sample.readlines()
testcol = []
for l in lines:
zipped = zip(testcol ,l)
输出为:
[(('1','a'),'apple'),(('2','b'),'banana'),(('3','c'),'cat'),(('4','d'),'dog')]
但我想要的是:
[('1','a','apple'),('2','b','banana'),('3','c','cat'),('4','d','dog')]
我必须将它放在循环中的原因是因为我的 sample.csv
可能包含任意数量的行。
这应该可以完成工作:
sample = open("sample.csv)
lines = [line.split() for line in sample.readlines()] #splitting on whitespace to create list of lists
zipped = zip(*lines)
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple.
我想创建一个 zip 循环 我有 sample.csv
文件,其中包含以下条目:
> 1 2 3 4
> a b c d
> apple banana cat dog
并具有以下代码:
sample= open("sample.csv)
lines = sample.readlines()
testcol = []
for l in lines:
zipped = zip(testcol ,l)
输出为:
[(('1','a'),'apple'),(('2','b'),'banana'),(('3','c'),'cat'),(('4','d'),'dog')]
但我想要的是:
[('1','a','apple'),('2','b','banana'),('3','c','cat'),('4','d','dog')]
我必须将它放在循环中的原因是因为我的 sample.csv
可能包含任意数量的行。
这应该可以完成工作:
sample = open("sample.csv)
lines = [line.split() for line in sample.readlines()] #splitting on whitespace to create list of lists
zipped = zip(*lines)
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple.