简体   繁体   English

在Python中,如何从文件创建2D列表并为每个子列表中的每个项目分配类型?

[英]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 读取每行包含的txt文件:国家/地区名称,区域,人口
  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 每个子列表都需要保留变量的类型,因此:每个子列表的string,float,int

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.

相关问题 从python中的每个子列表中创建第n个项目的列表 - Create a list of the n-th item from each sublist in python 如何为存储在一维列表中的每个项目分配一个随机变量? Output 必须是二维列表 - How to assign a random variable to each item stored in a 1D list ? Output has to be a 2D list 如何在 Python 中将文本文件(每个单独的项目在自己的行上)读入 2D 列表 - How to read a text file (each individual item on its own line) into a 2D list in Python 将项目的每个子列表添加到Python中的列表列表 - Add an Item each sublist to the list of Lists in Python 如何将字符串列表转换为子列表列表,每个子列表中的每个字符串? - How do you turn a list of strings into a list of sublists with each string in each sublist? 将子列表与列表的每个项目合并 - Merge sublist with each item of list 将 2D 列表项与 python 中的每个 rest 进行比较 - Comparing 2D list item with each of the rest in python 如何为每个子列表分配分数? - How to assign a score to each sublist? 遍历二维列表,将列表中一行的每个值分配给一个变量,对每一行重复 - python - Iterate through 2D List, assign each value on a row in the list to a variable, repeat for each row - python 如何将函数应用于python中列表的每个子列表? - How to apply a function to each sublist of a list in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM