Skip to main content
 首页 » 编程设计

python之python中的列表和文件

2025年05月04日18lonelyxmas

我正在使用 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