Reputation: 53
Sorry if that's an awkward title. Here's what I want to do:
A sample of what would be a long output is:
[['Afghanistan', '647500.0', '25500100'], ['Albania', '28748.0', '2821977'], ['Algeria', '2381740.0', '38700000'], ['American Samoa', '199.0', '55519'], ['Andorra', '468.0', '76246']
etc... and python needs to know the type of each variable, for example if i wanted to create a new function that sorts all floats in the list.
Here's what I have now, but it only returns each line as a sublist, and I believe doesn't know the type if I wanted to use this 2d list for new functions.
def Countries(filename):
f = open(filename)
lines = f.readlines()
f.close()
myList = []
for line in lines:
myList.append(line.strip().split(','))
return myList
Upvotes: 0
Views: 175
Reputation: 5515
the main problem you have is that f.readlines()
reads everything as a string. you can then map each item in your sublist through a type checker like this:
def typeCheck(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except:
return s
will try to explicitly cast your parameter as an 'int', then a 'float', then just leave it as is. it is this order because all things that can be cast as a 'int' can also be cast as a 'float' but not the other way around so you want to check for the int
first (ie, '123.1'
will raise an error for int('123.1')
but not float('123.1')
)
you can then append the mapped list like this:
for line in lines:
myList.append(list(map(typeCheck,line.strip().split(',')))
and your values that can be converted to floats and int will be converted.
EXAMPLE:
>>> def typeCheck(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except:
return s
>>> l = [['Afghanistan', '647500.0', '25500100'], ['Albania', '28748.0', '2821977'], ['Algeria', '2381740.0', '38700000'], ['American Samoa', '199.0', '55519'], ['Andorra', '468.0', '76246']]
>>> for i in l: print(list(map(typeCheck,i)))
['Afghanistan', 647500.0, 25500100]
['Albania', 28748.0, 2821977]
['Algeria', 2381740.0, 38700000]
['American Samoa', 199.0, 55519]
['Andorra', 468.0, 76246]
Upvotes: 0
Reputation: 31
Perhaps this is what you're looking for:
def Countries(filename):
f = open(filename)
myList = []
for line in f.readlines():
line_data = line.split(",")
myList.append(line_data)
return myList
But, if it's a .txt file I think it's only going to be returning strings. So, you'd have to convert types.
Upvotes: 2