Python:如何警告用户列表中的重复值

时间:2015-11-07 00:24:24

标签: python list duplicates append warnings

我试图编写一个允许用户输入尽可能多的整数的程序。正如您所看到的,他们将使用' lengthList = ....'来决定这一点。我的目标不仅是删除重复的条目,还要通知用户重复的条目。我设法删除了重复项,但无法解决如何通知用户其条目已被删除的问题。例如" 28已经输入。已从列表中删除。"

谢谢

{{1}}

2 个答案:

答案 0 :(得分:1)

尝试使用列表来存储值并在添加数字之前测试输入的值是否在其中。 下面是我对这个问题的解决方案:

l = []
while True:
    userNumber = input("Please input a number: ")
    if userNumber not in l:
        userNumber = l.append(userNumber)
        print(l)
    else:
        print(f'{userNumber} already exist in the list, and your list is {l}')

输出:

Please input a number: 1
['1']
Please input a number: 1
1 already exist in the list, and your list is ['1']
Please input a number: 2
['1', '2']
Please input a number: 2
2 already exist in the list, and your list is ['1', '2']
Please input a number: 3

答案 1 :(得分:0)

<强>尝试:

<span></span>@test<span></span>

<强>输出:

## Creating the results list
results = list()

## Casting the string input to int()
amount_of_numbers = int(input("Please enter the amount of numbers: "))

## While lenght of results is lower than the provided amount of numbers
while len(results) < amount_of_numbers:

    ## Casting the string input to int() since we want to store it as an integer and not as a string
    userNumber = int(input("Please input a number: "))

    ## If the input number is not already in results list
    if userNumber not in results:
        ## Appending the input number to results list
        results.append(userNumber)
    else:
        ## Printing a message saying that the number already exists in results list
        print "{} has already been entered".format(userNumber)
## Printing results list
print (results)
相关问题