简体   繁体   English

将用户输入添加到列表中,如果输入存在于列表中,则将其删除;如果输入不存在,则将其追加

[英]Adding user input to a list , then deleting it if the input exists in the list or appending it if it does not

So I want to ask a user to enter a letter for a pre-made list. 因此,我想请用户输入一个字母作为预制列表。 If that letter already exists in that list , I want to have that letter deleted , if it does not exists in the list , I want it appended to the list. 如果该字母已存在于该列表中,则我想删除该字母;如果该字母不存在于列表中,则希望将其追加到列表中。 This is the code I'm using right now : 这是我现在正在使用的代码:

list1= ['a','b','c','d','e']
letter=input("please input a letter ")
for letter in list1:
    if letter in list1:
         del list1[letter]
         print(list1)
    else:
         print(list1.append(letter)

It gives the type-error that list indices must be integers not string. 它给出了类型错误,即列表索引必须是整数而不是字符串。 How do I go about this ? 我该怎么办?

You will need to pop the letter at the index. 您将需要在索引处弹出字母。 Also there is no need for the for loop. 同样也不需要for循环。 Edited answer to incorporate @lukasz comment. 编辑答案以合并@lukasz评论。

list1= ['a','b','c','d','e']
letter=input("please input a letter ")
if letter in list1:
    list1.remove(letter)
else:
    print(list1.append(letter))

Pretty simple it is. 很简单。 Remove the value if it exists in the list, append if not. 如果该值存在于列表中,则将其删除;否则,将其追加。

list1= ['a','b','c','d','e']
letter=raw_input("please input a letter ")
list1.remove(letter) if letter in list1 else list1.append(letter)

If the letter is in list1 , you can use remove to delete it, and append can be used to add the new letter to the end of the list. 如果字母在list1 ,则可以使用remove删除它,并可以使用append将新字母添加到列表的末尾。 The following script lets you see it working: 以下脚本可让您看到它的工作原理:

list1 = ['a','b','c','d','e']

while True:
    print('Current list:', list1)
    letter = input("Please input a letter: ")

    if letter in list1:
        list1.remove(letter)
    else:
        list1.append(letter)

For example: 例如:

Current list: ['a', 'b', 'c', 'd', 'e']
Please input a letter: f
Current list: ['a', 'b', 'c', 'd', 'e', 'f']
Please input a letter: b
Current list: ['a', 'c', 'd', 'e', 'f']
Please input a letter: a
Current list: ['c', 'd', 'e', 'f']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM