我如何确定触发哪个if语句?
示例:
string = "hello"
if len(string) > 10:
print("over 10")
elif string == "hello":
print("String is equal to hello")
else:
pass
我想重写它以及它更多" pythonic",我已经到了这么远
string = "hello"
if len(string) > 10 or string == "hello":
print("one of the if statements was triggered") # I want to determine which was triggered
else:
pass
我希望尽可能完成什么?
由于
答案 0 :(得分:1)
IMO,您使用的if语句没有任何问题。
但如果你想要聪明,可以使用lambda
的列表:
In [1]: string = 'Hello'
In [2]: conditions = [lambda s: 'Length is > 10' if len(s) > 10 else None,
...: lambda s: 'String is "Hello"' if s == 'Hello' else None]
conditions
是匿名函数。它们使用三元运算符返回描述条件的字符串或None
。
这与您的if
声明略有不同,因为它会测试所有条件。
我们将函数应用于字符串,过滤掉None
值:
In [3]: results = [r for r in [c(string) for c in conditions] if r is not None]
results
是描述适用于字符串的条件的字符串列表。
我们打印结果。
In [4]: for r in results:
...: print(r)
...:
String is "Hello"
这当然很好地利用了Python提供的可能性。
如果你认为这个Pythonic是一个品味问题。 :-)原始if
- 语句更短,可能更容易阅读!特别是对于Python新手。
但是,如果你想测试很多条件,这可能是一个很好的方法,而不是巨大的 if语句列表。