【问题标题】:How do I index a list to find a specific value and its location?如何索引列表以查找特定值及其位置?
【发布时间】:2022-01-14 09:50:07
【问题描述】:

我正在尝试编写一个代码,它将电影存储在一个列表中,我可以通过要求按位置添加电影或检查它是否在列表中来检索该列表。到目前为止,我一直在研究检索部分,但我不断收到错误消息,其中“'list' 对象的描述符'index' 不适用于'str' 对象”。 这是我目前的代码

myFile = open("movies.txt", "a")
more = "yes"
while more.lower() == "yes":
    movie = input("Please enter a movie title: ")
    myFile.write(movie + '\n')
    more = input("Would you like another item? Enter 'yes' or 'no'. ")
    find = input("Would you like to find a movie? Enter 'yes' or 'no'. ")
    myFile.close()
    if find == "yes":
        myFile = open("movies.txt")
        xlist = list[myFile]
        f2 = input("What movie would like to find?")
        f3 = xlist.index(f2)
        print(f2 + " is in number " + f3 + " on the list")

【问题讨论】:

  • list[myFile] - 这并没有你认为的那样
  • 这能回答你的问题吗? How to read a file line-by-line into a list?
  • 使用 myFile.readlines() 逐行读取文件而不是 list[myFile]
  • 现在问题是输出是:'str'对象没有属性'restrip'。刚刚尝试了 readlines() 但它只是说我的值(随机 a)不在列表中
  • rstrip,而不是restrip。 r 代表右,l 代表左。

标签: python list file indexing


【解决方案1】:

问题不在xlist 而是在f2,因为input() 返回字符串。如果输入数字 2,你的行看起来就像你写的:

f3 = xlist.index("2")

相反,将输入转换为整数:

try:
    f2 = int(input("What movie would like to find?"))
except ValueError:
    exit("Invalid number")

【讨论】:

    【解决方案2】:

    说明

    在代码的第 11 行

    xlist = list[myFile]

    要制作包含在文件movies.txt 中的单词列表,您可以这样做

    xlist=myFile.read().splitlines()

    代码

    myFile = open("movies.txt", "a")
    more = "yes"
    while more.lower() == "yes":
        movie = input("Please enter a movie title: ")
        myFile.write(f'{movie}\n')
        more = input("Would you like another item? Enter 'yes' or 'no'. ")
        find = input("Would you like to find a movie? Enter 'yes' or 'no'. ")
        myFile.close()
        if find == "yes":
            myFile = open("movies.txt")
            xlist=myFile.read().splitlines()
            print(xlist)
            f2 = input("What movie would like to find?")
            f3 = xlist.index(f2)
            print(f'{f2}  is in number {f3} on the list')
    

    输出

    Please enter a movie title: money-heist
    Would you like another item? Enter 'yes' or 'no'. no
    Would you like to find a movie? Enter 'yes' or 'no'. yes
    ['Dark', 'money-heist']
    What movie would like to find?Dark
    Dark  is in number 0 on the list
    

    【讨论】:

    • 请说明您对原始代码进行更改的位置以及原因。否则它只是 OP 的复制/粘贴操作,没有任何学习效果
    • okk thx @ThomasWeller 提醒我这一点。稍等一下,我正在做更改
    • 我做了更改现在可以了吗@ThomasWeller
    • 所以浏览编辑后的代码,并确保我理解这一点,.splitlines() 将文件中的行分隔为可用信息,而波浪形括号以不同的方式读取变量?
    • 并且通过使用 f'{movie} 和 f'{f2},我们可以将每行的两者连接起来吗?这样做比使用循环解析它更有意义。非常感谢!
    猜你喜欢
    • 2023-03-05
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多