[英]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: 这是我想做的:
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. 等...和python需要知道每个变量的类型,例如,如果我想创建一个对列表中所有浮点数进行排序的新函数。
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
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. 但是,如果它是.txt文件,我认为它只会返回字符串。 So, you'd have to convert types. 因此,您必须转换类型。
the main problem you have is that f.readlines()
reads everything as a string. 您遇到的主要问题是f.readlines()
将所有内容读取为字符串。 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. 会尝试将您的参数显式转换为'int',然后是'float',然后将其保留不变。 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')
) 之所以这样,是因为所有可以转换为“ int”的事物也可以转换为“ float”,但反之亦然,因此您要先检查int
(即'123.1'
会引发错误)对于int('123.1')
而不是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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.