Reputation: 379
I want to create a loop of zips I have sample.csv
file with the below entries:
> 1 2 3 4
> a b c d
> apple banana cat dog
and have the below code:
sample= open("sample.csv)
lines = sample.readlines()
testcol = []
for l in lines:
zipped = zip(testcol ,l)
The output is:
[(('1','a'),'apple'),(('2','b'),'banana'),(('3','c'),'cat'),(('4','d'),'dog')]
but what i want is:
[('1','a','apple'),('2','b','banana'),('3','c','cat'),('4','d','dog')]
The reason why i have to put it in loops is because my sample.csv
may contain arbitrary number of rows.
Upvotes: 0
Views: 56
Reputation: 800
This should do the job:
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.
Upvotes: 1