简体   繁体   English

在python中使用三元运算符?

[英]Using ternary operator in python?

Consider the following code snippet. 请考虑以下代码段。 It flags a syntax error at the break statement. 它在break语句中标记语法错误。

digits = list(str(102))
dummy = list(str(102/2))
for j in digits:
    dummy.remove(j) if j in dummy else break

How do I fix this?(I want to still use the ternary operator) 我该如何解决这个问题?(我还想使用三元运算符)

Edit: 编辑:

(see my conversation with Stefan Pochmann in the comments) (参见我在评论中与Stefan Pochmann的谈话)

Ternary operator is not for only statement, but rather for assignment or for expression (and break is an only statement): 三元运算符是不是声明,而是转让或表达(和break唯一的语句):

a = 5 if cond else 3 #OK
do() if cond else dont() #also OK
do() if cond else break #not OK

use normal if-else statement to do statements: 使用普通的if-else语句来执行语句:

if cond:
    do()
else:
    break

You cannot use break in Your loop logic can be re written using itertools.takewhile if you want a more succinct solution 你不能使用break你的循环逻辑可以使用itertools.take重写,如果你想要一个更简洁的解决方案

digits = list(str(102))
dummy = list(str(102/2))

from itertools import takewhile

for d in takewhile(dummy.__contains__, digits):
    dummy.remove(d)

You can also remove the need for the else using a for loop by reversing your logic, check if j is not in dummy breaking when that is True: 您还可以通过反转逻辑来使用for循环删除对else的需要,检查j是否在虚拟中断时为True:

for j in digits:
    if j not in dummy:
        break
    dummy.remove(j)

Also if you want to remove all occurrences of any of the initial elements from digits that are in dummy, remove won't do that for any repeating elements but using a list comp after creating a set of elements to remove will: 此外,如果要从虚拟数字中删除所有出现的任何初始元素,则删除不会对任何重复元素执行此操作,但在创建要删除的元素集后使用list comp将:

digits = str(102)
dummy = list(str(102/2))
st = set(takewhile(dummy.__contains__, digits))
dummy[:] = [d for d in dummy if d not in st]

print(dummy)

You can also iterate over a string so no need to call list on digits unless you plan on doing some list operations with it after. 你也可以迭代一个字符串,所以不需要在数字上调用列表,除非你计划用它做一些列表操作。

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

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