我正在使用 python 中的 readlines
方法来获取所有数据行的列表。现在我不想访问该列表中的某些索引:
file = open('article.txt', 'r')
data = file.readlines()
print data.index(1)
Error: data isn't a list
怎么了?
最佳答案
我想你的意思是(如果你的目标是打印列表的第二个元素):
print data[1]
data.index(value)
返回value
的列表位置:
>>> data = ["a","b","c"]
>>> data[1] # Which is the second element of data?
b
>>> data.index("a") # Which is the position of the element "a"?
0
>>> data.index("d") # Which is the position of the element "d"? --> not in list!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list
关于python - python中的列表和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4368812/