【问题标题】:ValueError: list.remove(x) : x not in listValueError: list.remove(x) : x 不在列表中
【发布时间】:2022-12-17 23:07:56
【问题描述】:

我正在尝试编写一个程序来查看给定字符串中的字母是否重复,但我遇到了一个问题(错误)“ValueError:list.remove(x):x 不在列表中”检查下面的代码我在我的程序中使用。

import random

word = input("write the word that you want to permutate in all different ways  : ")
n = len(word)

def check() :
    s = set ()
    list = [0]
    i = 0

    while True :
        i  = i+1
        if i == n :
            break
        list.append(i)
        
    print(list)

    while True :
        number = random.randint(0,n-1)
        list.remove(number)
        checknum = random.choice(list)
        if checknum == number :
            checknum = random.randint(0,n-1)
        if word[number] == word[checknum] :
            print("there is a repetition of characters in the given string.....")

        if len(list) == 0 :
            break

check()

【问题讨论】:

  • 您好,欢迎来到 StackOverflow!附带说明一下,您应该避免使用像 list 这样的内置函数作为变量名。
  • 如果您尝试删除例如会发生什么7两次?

标签: python list


【解决方案1】:

首先,你真的应该避免使用内置类型作为你的变量名(你可以使用 number_list 而不是列表)。

关于你的问题 - 这是一个反问题 - 如果你删除一个随机数它会再次随机化会发生什么?

【讨论】:

  • 评论应该张贴在评论部分而不是作为答案
【解决方案2】:

在下面的代码中,random.choice() 方法用于从列表中选择一个随机数,而不是使用 random.randint()。这确保所选数字始终在列表中,并避免“ValueError:

import random

word = input("write the word that you want to permutate in all different ways  : ")
n = len(word)

def check() :
    s = set ()
    list = [0]
    i = 0

    while True :
        i  = i+1
        if i == n :
            break
        list.append(i)
        
    print(list)

    while True :
        # Use the random.choice() method to choose a random number from the list, instead of using random.randint()
        number = random.choice(list)
        # Check if the number is in the list before trying to remove it
        if number in list:
            list.remove(number)
        checknum = random.choice(list)
        if checknum == number :
            checknum = random.randint(0,n-1)
        if word[number] == word[checknum] :
            print("there is a repetition of characters in the given string.....")

        if len(list) == 0 :
            break

check()

【讨论】:

    猜你喜欢
    • 2018-07-05
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多