0

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.

1 Answer 1

1

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)

See Unpacking Argument Lists:

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for this. zip(*lines) only took the first letter of apple,banana.cat and egg. Also, the reason why i wanted this to e successively zipped is that i may exclude some rows inside the csv file. Thanks.
@pythonnovice Check the edit. Each line from csv is split on whitespace so it should work now.
@pythonnovice If you want to exclude some rows, you can do something like this: lines = [line.split() for line in sample.readlines() if isGood(line)], where isGood(line) is a method that will return true if the line should be included.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.