【问题标题】:How to remove all elements of five from a list [duplicate]如何从列表中删除五个的所有元素[重复]
【发布时间】:2017-02-05 17:26:37
【问题描述】:

我的代码返回“无”。 如果我的问题不清楚,如果我选择列表 [1 , 3 , 4 , 5 ,5 , 7],我希望返回列表 [1 , 3 , 4 , 7] 。我的代码如下:

print("This program takes a list of 5 items and removes all elements of 5: ")

    list4 = []
    list4.append(input("Please enter item 1:"))  
    list4.append(input('Please enter item 2:'))  
    list4.append(input('Please enter item 3:'))  
    list4.append(input('Please enter item 4:'))
    list4.append(input('Please enter item 5:'))
    def remove_five():
        while 5 in list4:
            list4.remove(5)
    print(remove_five())

【问题讨论】:

  • 你读的是字符串。您尝试删除的是int。此外,您的 remove_five() 函数不会返回任何内容。
  • 你打印了一个什么都不返回的方法(所以 None)
  • remove_five 不返回任何内容
  • 我想还没有人提到这个,但是remove_five 没有返回任何东西:-P
  • 您正在检查一个 int。您需要检查字符串 '5'

标签: python


【解决方案1】:

这次使用列表推导可能会派上用场。

num_list = [1 , 3 , 4 , 5 ,5 , 7]
num_list = [int(n) for n in num_list if int(n)!=5]
print(num_list)

输出:

[1, 3, 4, 7]

注意:对字符串变量使用强制转换,如下所示:

num_list = [int(n) for n in num_list if int(n)!=5]

【讨论】:

  • 改用map[n for n in map(int, num_list) if n != 5]
【解决方案2】:

您的代码打印 None 因为您的函数没有 return 语句。

如果你像这样打印,你会看到列表没有变化,因为你的列表中没有5s,你有'5'(一个字符串)

remove_fives() 
print(list4) 

如果要添加整数,而不是字符串,则需要强制转换

append(int(input

如果您想创建一个没有五的列表,请尝试列表理解

no_fives = [x for x in list4 if x!=5]

或者将输入保持为字符串

no_fives = [x for x in list4 if x!='5']

【讨论】:

    【解决方案3】:

    改变这个:

    def remove_five():
        while 5 in list4:
            list4.remove(5)
    

    到这里:

    def remove_five():
        while '5' in list4:
            list4.remove('5')
        return list4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      相关资源
      最近更新 更多