【问题标题】:While not in list [closed]虽然不在列表中[关闭]
【发布时间】:2012-08-04 13:10:47
【问题描述】:

我正在尝试编写代码,我想问你如何让 while 循环重复直到找到一个单词,在我的例子中 END 在列表中,例如.

L=[]
while "END" (not) in L :
   L=L.append(something)

如果你不明白我的意思,可以问我。

【问题讨论】:

  • 为什么END会突然出现在L中? something 来自哪里?
  • @Tichodroma 那东西可能包含 END。
  • 你的意思是这样的吗? L=[] ... while something != 'END': L.append(something)
  • 虽然不是“END”在 L = 类型错误
  • 我不确定人们认为这个问题有什么问题。 OP 有明确的目标和一段非功能性代码。

标签: python python-3.x while-loop


【解决方案1】:
>>> a = [1,2,3]
>>> while 12 not in a:
...  a.append(len(a)+1)
...
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

例如...

【讨论】:

  • +1 用于正确解析问题:-)
【解决方案2】:

您编写的代码可以正常工作,除了 list.append() 返回 None 并就地修改列表;不要将其分配回 L:

L=[]
while "END" not in L :
   L.append(something)

【讨论】:

    【解决方案3】:

    如果你有一个清单,这就是你可以达到预期结果的方法。

    for something in somethings:
        if something != "END":
            L.append(something)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 2023-03-06
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多