[英]Reading files from python and adding to a list with correct value type
I am reading a file in python and i need to add every line to a list.我正在用 python 读取文件,我需要将每一行添加到列表中。 The problem is that every line is a list containing string and integers.
问题是每一行都是一个包含字符串和整数的列表。 This is the file i am reading: file
这是我正在阅读的文件:文件
this is the output of reading the file and putting it on the new list.这是读取文件并将其放入新列表的输出。 output
输出
as you can see it is storing me the lines as a string but it need to be like this: correct output如您所见,它正在将我的行存储为字符串,但它需要像这样:正确的输出
CODE:代码:
def build_sets(f):
lista_valores = []
with open(f, 'r') as f:
for line in f:
lista_valores += line.strip().split('\n')
print(lista_valores)
#pass
Try this in your for
loop:在你的
for
循环中试试这个:
lista_valores = line.strip('][').split(', ')
Also please only use english words to define your variables, it's one of the main rules of variable naming conventions.另外请只使用英文单词来定义您的变量,这是变量命名约定的主要规则之一。
Use ast.literal_eval with which you can safely evaluate an expression node or a string containing a Python literal or container display.使用 ast.literal_eval 可以安全地评估表达式节点或包含 Python 文字或容器显示的字符串。 Hence it will evluate your string as a proper list.
因此它会将您的字符串评估为正确的列表。
import ast
def build_sets(f):
lista_valores = []
with open(f, "r") as f:
a = f.read().splitlines()
for item in a:
lista_valores.append(ast.literal_eval(item))
print(lista_valores)
Output:输出:
[[1, 'a', 'b'], [2, 'b', 'c']]
thank you guys, i figured it out this way: lista_valores = []谢谢你们,我是这样想出来的:lista_valores = []
with open(f, 'r') as f:
for line in f:
linha = line[0:len(line)-1].strip("[]").split(',')
lista_valores.append(linha)
for i in range(len(lista_valores)): # convert to int
for j in range(len(lista_valores[i])):
if lista_valores[i][j].isdigit():
lista_valores[i][j] = int(lista_valores[i][j])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.