【问题标题】:why this code doesn't work i am using python3?为什么这段代码不起作用我正在使用python3?
【发布时间】:2018-05-20 17:23:23
【问题描述】:

我想删除列表中的值

lists = [12,15,15,15,3,15,1,6,4,7,888,56248]
while len(lists) is True:
    lists.pop()
print(lists)

但我得到了这个输出:

[12, 15, 15, 15, 3, 15, 1, 6, 4, 7, 888, 56248]

【问题讨论】:

  • len(lists) 是一个整数。整数与布尔单例True 永远不是同一个对象。也许你的意思只是while lists
  • @Matthias 同意并敲开了。副本正在谈论在改变列表时迭代列表。这只是对条件的误解。
  • 您可以使用while lists: lists.pop()。更好的解决方案是lists = []。如果它必须是相同的列表(具有相同的 id),请使用 lists[:] = []
  • @Matthias lists.clear()
  • 很公平。错误的条件是主要问题。而且我的欺骗目标不适用,因为他从列表的末尾弹出,这是安全的。对此感到抱歉。

标签: python python-3.x list


【解决方案1】:

如果“删除”是指删除元素并减少列表,则可以使用 for 循环遍历列表副本:

for n in lists[:]:
    lists.remove(n)

相反,如果您希望拥有一个与列表一样长的 None(或 0)值列表,您可以这样做:

newlists = [0] * len(lists)

正如前面评论中所建议的那样。

【讨论】:

    【解决方案2】:

    这里的问题在于你的条件

    while len(lists) is True:
    

    is 检查身份,而不是平等。

    [1, 2, 3] == [1, 2, 3]  # True
    [1, 2, 3] is [1, 2, 3]  # False, they are two distinct (but equivalent) lists.
    

    然而,这里即使相等也是不正确的,因为

    42 == True           # False
    2 == True            # False
    any_nonzero == True  # False
    # notably 1 == True
    # and     0 == False
    # but still (1 is True) == False!
    

    您可以将整数强制转换为布尔值

    bool(42) == True           # True
    bool(2) == True            # True
    bool(any_nonzero) == True  # True
    

    但通常最好将强制留给 Python

    while lists:
        lists.pop()
    # or more simply:
    # lists = []
    

    【讨论】:

    • 是的,你是对的,我忘记了。我应该把它放在 bool() 中。谢谢
    • 因为0 在python 中表示False,其他任何东西都是真的。这意味着代码将继续删除值,直到语句为假(当列表中没有值时)。
    • @StefanPochmann 都可以,但你说得对,while lists 更好。我会编辑
    • @AJ123 没有别的。空字符串("")和相关的空集合([]{}set() 等)也是 Falsey。 while lists 绝对是惯用的方法。
    猜你喜欢
    • 2010-09-18
    相关资源
    最近更新 更多