gpt4 book ai didi

python - python中的列表和文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:21:35 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com