Python:从文件中导入数组,索引完好无损
Python: Import array from file with indexes intact
我有一个文件,我想将其导入到一个数组中,但将每个条目作为索引,以便我可以调用每个特定的条目。
文件(testing_array.txt):
["zero", "one", "two", "three", "four", "five"]
脚本:
f = open('testing_array.txt').read()
array = [f]
print (array[0])
print (array[1])
输出:
["zero", "one", "two", "three", "four", "five"]
Traceback (most recent call last):
File "testing_array.py", line 4, in <module>
print (array[1])
IndexError: list index out of range
我已尝试对每个索引的每个条目进行 .insert
循环,但未成功。我 3 天前才开始编写脚本 python,所以如果我忽略了一些基本的东西,我深表歉意。如有任何帮助,我们将不胜感激。
尝试使用 json 序列化程序(它与 list 的语法相同)。
import json
my_list = json.loads('["zero", "one", "two", "three", "four", "five"]')
您也可以删除方括号并将行拆分为列表。
>>> line = '["zero", "one", "two", "three", "four", "five"]'
>>> line.strip("[]").split(",")
['"zero"', ' "one"', ' "two"', ' "three"', ' "four"', ' "five"']
我有一个文件,我想将其导入到一个数组中,但将每个条目作为索引,以便我可以调用每个特定的条目。
文件(testing_array.txt):
["zero", "one", "two", "three", "four", "five"]
脚本:
f = open('testing_array.txt').read()
array = [f]
print (array[0])
print (array[1])
输出:
["zero", "one", "two", "three", "four", "five"]
Traceback (most recent call last):
File "testing_array.py", line 4, in <module>
print (array[1])
IndexError: list index out of range
我已尝试对每个索引的每个条目进行 .insert
循环,但未成功。我 3 天前才开始编写脚本 python,所以如果我忽略了一些基本的东西,我深表歉意。如有任何帮助,我们将不胜感激。
尝试使用 json 序列化程序(它与 list 的语法相同)。
import json
my_list = json.loads('["zero", "one", "two", "three", "four", "five"]')
您也可以删除方括号并将行拆分为列表。
>>> line = '["zero", "one", "two", "three", "four", "five"]'
>>> line.strip("[]").split(",")
['"zero"', ' "one"', ' "two"', ' "three"', ' "four"', ' "five"']