morr0564
morr0564

Reputation: 53

In Python, how do you create a 2D list from a file and assign a type to each item in each sublist?

Sorry if that's an awkward title. Here's what I want to do:

  1. Read a txt file that on each line contains: country name, area, population
  2. Each line turns into a sublist within a main list
  3. Each sublist needs to retain the type of variable, so: string,float,int for each sublist

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

Answers (2)

R Nar
R Nar

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

Jeremy Thompson
Jeremy Thompson

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

Related Questions