【问题标题】:Python: continue loop in one string if [closed]Python:如果[关闭],则在一个字符串中继续循环
【发布时间】:2018-10-21 15:25:49
【问题描述】:

这是抽象代码的示例(我的任务不是获取唯一项)

lst = [1, 1, 2, 2, 2, 3, 3]
uniq = []
for i in lst:
    if i in uniq:
        continue
    uniq.append(i)
    print(str(i))  # other useful code

我想在 else 语句中使用 continue 运算符编写单字符串 if。示例

uniq.append(i) if i not in uniq else continue

怎么做才对?

【问题讨论】:

  • 只要使用uniq = list(set(lst))
  • 我的任务不是获得独特的物品
  • @AlexFrolov 那么你为什么要问一个关于制作独特物品列表的问题呢???
  • python 中没有这样的语法。您可以在一行中使用if,在下一行中使用else
  • continue 是一个语句,不能在三元表达式中。

标签: python for-loop


【解决方案1】:

Python 中没有这样的语法。

你能得到的最接近一行的是行:

lst = [1, 1, 2, 2, 2, 3, 3]
uniq = []
for i in lst:
    if i not in uniq: uniq.append(i)    # <----
    else: continue                      # <----
    print(str(i))  # other useful code

试图将所有内容放在一行 (if i not in uniq: uniq.append(i); else: continue) 会导致语法错误。

你提到的语法(uniq.append(i) if i not in uniq else continue)是一个三元表达式,作为一个表达式,它不能包含continue,这是一个语句。 p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2020-09-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多