Burn4live
Burn4live

Reputation: 55

Convert a string in a few int between commas in python

I am getting a number from a csv file to a list and would like to compare these numbers to other numbers, how can I achieve this?

num = [2,32,31,23,12,32]

csvnumber= ['23,43,41,21,34']

How do I convert the csv number into ints to compare with my num list?

Upvotes: 1

Views: 67

Answers (3)

whoan
whoan

Reputation: 8521

You can do it with list comprehensions and the int factory function:

[ int(i) for i in csvnumber[0].split(',') ]

Example

>>> csvnumber=['23,43,41,21,34']
>>> [ int(i) for i in csvnumber[0].split(',') ]
[23, 43, 41, 21, 34]

Upvotes: 2

Malik Brahimi
Malik Brahimi

Reputation: 16711

Just make a new list, split the current list at the commas, and append the items as integers like so:

new_csvnumber = []

for i in csvnumber[0].split(','):
    new_csvnumber.append(int(i))

Upvotes: 0

user4447887
user4447887

Reputation:

x= ['23,43,41,21,34']

t=list(map(int, x[0].split(',')))

print (t)

Assume your list has only one element as your example.Output:

>>> 
[23, 43, 41, 21, 34]
>>> 

Then reach each element in the list t with a for loop and append them to your list num.

Upvotes: 1

Related Questions