Reputation: 45
This is my code:
names = []
filename = "names.csv"
filedir = ""
csv_file = os.path.join(filedir, filename)
with open(csv_file) as file:
reader = csv.reader(file)
for row in reader:
name = row
names.append(name)
print(names)
This is the output I am getting:
[['hello'], ['hello'], ['one'], ['two'], ['three']]
The output I want is:
['hello', 'hello', 'one', 'two', 'three']
I don't know why this is happening. If you can help, thanks in advance.
Upvotes: 0
Views: 45
Reputation: 77
One line solution:
names = [['hello'], ['hello'], ['one'], ['two'], ['three']]
list(map(lambda x: x[0], names))
Upvotes: 0
Reputation: 518
A simplest way to do this:
for row in reader:
[name] = row
names.append(name)
print names
Upvotes: 0
Reputation: 1747
This is happening because csv.reader
iterates through the rows as lists.
It seems you only have a single element in each row of your csv?
If that is indeed the case, and is always the case, you can do two different things:
1)
with open(csv_file) as file:
reader = csv.reader(file)
for row in reader:
name = row
names.append(name[0])
2)
with open(csv_file) as file:
reader = csv.reader(file)
for row in reader:
name = row
names.extend(name)
Extend unpacks an iterable into the list.
Upvotes: 0
Reputation: 499
You can do this on names:
x=[['hello'], ['hello'], ['one'], ['two'], ['three']]
t = []
for i in x:
for j in i:
t.append(j)
or you can do the below in your case:
names = []
for row in reader:
names.append(row[0])
Upvotes: 1
Reputation: 760
using default list:
new_names = [name for names_list in names for name in names_list]
using numpy:
import numpy as np
new_names = np.array(names).flatten()
Upvotes: 0