[英]Reading files from a csv file with python showing the first list and not displaying appended files in the correct order
[英]Reading files from python and adding to a list with correct value type
在你的for
循環中試試這個:
lista_valores = line.strip('][').split(', ')
另外請只使用英文單詞來定義您的變量,這是變量命名約定的主要規則之一。
使用 ast.literal_eval 可以安全地評估表達式節點或包含 Python 文字或容器顯示的字符串。 因此它會將您的字符串評估為正確的列表。
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)
輸出:
[[1, 'a', 'b'], [2, 'b', 'c']]
謝謝你們,我是這樣想出來的: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.