Keep on getting ValueError: invalid literal for int() with base 10: '1, 7'

Keep on getting ValueError: invalid literal for int() with base 10: '1, 7'

我正在尝试制作像游戏一样的刽子手,但是当我 运行 我目前拥有的这段代码时,我不断出错,我尝试制作新的变量,例如 int1 和 int2 但是徒劳无功。这是代码:

from nltk.corpus import words
import random

word_list = words.words()
password = random.choice(word_list)
finish = len(password)

print("The password has", len(password),"letters")
print(password)

while finish > 0:
    
    guess = input("Please enter a letter to see where it is in the word:  ")
    occur = password.count(guess)
    
    mylist = {', '.join([str(i) for i, c in enumerate(password) if c == guess])}
    print(mylist)

    int1 = [int(y) for y in mylist]

    int2 = [x+1 for x in mylist]
    print(ints)

    if len(guess) > 1 or len(guess) < 1:
        print("Enter 1 standard keyboard letter to see if it is in the word")
    
    elif guess in password:
         print(f"This letter is at position {', '.join([str(i) for i, c in enumerate(password) if c == guess])} in the word")
         finish = finish - occur
         password = password.replace(guess,'.')
         print("Only", finish, "letters left to guess")
         
    else:
        print("Try again")

我想要第 16-22 行做的是首先将列表的元素从字符串转换为整数,然后打印出列表,然后再次打印出相同的列表,但将 1 添加到每个元素名单。 这是我不断收到的错误:

Traceback (most recent call last):
  File "/Users/ARR2K18/Desktop/Hangman.py", line 29, in <module>
    int1 = [int(y) for y in mylist]
  File "/Users/ARR2K18/Desktop/Hangman.py", line 29, in <listcomp>
    int1 = [int(y) for y in mylist]
ValueError: invalid literal for int() with base 10: '1, 7'

需要一些帮助

您的问题在这里:

mylist = {', '.join([...])}
print(mylist)

int1 = [int(y) for y in mylist]

', '.join(...) 会给你一个像“1, 7”这样的结果,集合看起来像 {"1, 7", "3, 4", ... }。然后,当您在这些集合元素之一上调用 int() 时,您会看到显示的错误。

解决这个问题的方法可能是简单地放弃 join 调用并单独使用列表理解。