Reputation: 319
I was trying to read a csv file:
SigGenelist = []
Sig = csv.reader(open('Genelist.csv'))
for row in Sig:
SigGenelist.append(row)
print (SigGenelist)
the print out was like:
[['x'], ['0610010K14Rik'], ['0610011F06Rik'], ['1110032F04Rik'], ['1110034G24Rik'], ...
so I got a nested list, but I would like to have a list with each element as string, something like:
['x', '0610010K14Rik', '0610011F06Rik', '1110032F04Rik', '1110034G24Rik', ...
I tried to convert element into string like:
SigGenelist = []
Sig = csv.reader(open('Genelist.csv'))
for row in Sig:
row = str(row) # try to change row into string instead of list
SigGenelist.append(row)
print (SigGenelist)
but did not get what I would like to...
["['x']", "['0610010K14Rik']", "['0610011F06Rik']", "['1110032F04Rik']","['1110034G24Rik']"...
Any suggestion?
Upvotes: 3
Views: 2442
Reputation: 3954
Use the sum
builtin function, since csv.reader
returns a generator, the following code will do the job:
Sig = csv.reader(open('Genelist.csv'))
SigGenelist = sum(Sig, [])
Upvotes: 0
Reputation: 9010
This might be idiomatic:
from itertools import chain
csv_reader = csv.reader(open('Genelist.csv'))
SigGeneList = list(chain.from_iterable(csv_reader))
Upvotes: 1
Reputation: 7690
Instead of append
try using +
operator, change your line
...
SigGenelist.append(row)
...
to use +=
:
...
SigGenelist += row
...
Append is used to add a single element to your list, while += and extend is used to copy the list on the right hand side to the left hand side. And since extend is more expensive due to an additional function call (not that it matters, difference is very small), += is a good way in your situation.
Upvotes: 3
Reputation: 14216
Change this:
SigGenelist.append(row)
To this:
SigGenelist.extend(row)
Upvotes: 1
Reputation: 401
Try this:
my_list = [[1], [2], [3], [4], [5], [6]]
print [item for sublist in my_list for item in sublist]
This is a list comprehension that will flatten a list of lists into a single list.
Or, maybe the simpler option is not appending, but adding the rows to the list.
SigGenelist = []
Sig = csv.reader(open('Genelist.csv'))
for row in Sig:
SigGenelist += row
print (SigGenelist)
.append
will add the entire list to the end of the list, resulting in the nested lists. +=
will just concatenate the lists, making it a list of depth 1!
Upvotes: 1