Python 来自文件的嵌套列表
Python nested list from file
假设我有以下 .txt 文件:
"StringA1","StringA2","StringA3"
"StringB1","StringB2","StringB3"
"StringC1","StringC2","StringC3"
我想要一个嵌套列表,格式为:
nestedList = [["StringA1","StringA2","StringA3"],["StringB1","StringB2","StringB2"],["StringC1","StringC2","StringC3"]]
所以我可以像这样访问 StringB2:
nestedList[1][1]
最好的方法是什么?我没有大量的数据,最多可能有 100 行,所以我不需要数据库或其他东西
file = open('a.txt').read()
file
l=[]
res = file.split('\n')
for i in range(len(res)):
l.append(res[i].split(','))
print(l[1][1])
假设您的文件名为 a.txt 的数据格式与您在问题中指定的格式相同,即换行符分隔以便我们可以添加嵌套列表,并且其中的数据以 ,(逗号)分隔。上面的代码会给你正确的输出。
您可以使用此示例代码:
with open('file.txt') as f:
nestedList = [line.split(',') for line in f.readlines()]
print(nestedList[1][1])
假设我有以下 .txt 文件:
"StringA1","StringA2","StringA3"
"StringB1","StringB2","StringB3"
"StringC1","StringC2","StringC3"
我想要一个嵌套列表,格式为:
nestedList = [["StringA1","StringA2","StringA3"],["StringB1","StringB2","StringB2"],["StringC1","StringC2","StringC3"]]
所以我可以像这样访问 StringB2:
nestedList[1][1]
最好的方法是什么?我没有大量的数据,最多可能有 100 行,所以我不需要数据库或其他东西
file = open('a.txt').read()
file
l=[]
res = file.split('\n')
for i in range(len(res)):
l.append(res[i].split(','))
print(l[1][1])
假设您的文件名为 a.txt 的数据格式与您在问题中指定的格式相同,即换行符分隔以便我们可以添加嵌套列表,并且其中的数据以 ,(逗号)分隔。上面的代码会给你正确的输出。
您可以使用此示例代码:
with open('file.txt') as f:
nestedList = [line.split(',') for line in f.readlines()]
print(nestedList[1][1])