如果X或Y或Z然后使用*那个*?

时间:2018-08-10 19:27:10

标签: python python-3.x

是否有一种方法可以编写可以包含许多参数的If(或等效参数)语句,并且如果其中任何一个满足逻辑要求,请使用 that 变量?

例如

if len(x) == 1 or len(y) == 1 or len(z) == 1 or ... len(zz) == 1:
    # do something with the variable that met the condition

因此,假设只有z的长度为1,我是否可以采用第一个True答案并使用该答案的方式写上面的想法/公式?

类似

x = "123"
y = "234"
z = "2"
xx = "1234"
yy = "12345"

if len(x) == 1 or len(y) == 1 or len(z) == 1 or len(xx) == 1 or len(yy) == 1:
    #do something with the variable that satisfies the condition, so `z` in this case.

这有意义吗?变量的长度可以随时更改,因此我想说“如果满足任何条件,请使用满足条件的变量” ...?

在上面,我事先不知道z是唯一符合条件的人,因此我的Then语句不能是z = "new value"或我想要的任何内容 与之相关。

编辑:对不起,每条评论我都不知道对整数进行len检查。这仅出于说明目的,这是我想到的“测试”的第一件事。很抱歉,len位是否令人困惑。我主要是想知道是否可以在不知道我的多个变量中的哪一个满足条件的情况下使用If语句(或相关语句)。 (我对python还是很陌生,所以对我缺乏语义或适当术语深表歉意)。我想尽可能避免使用elif,因为它可能变得很粘。 (但是,如果那是最pythonic的方式,那就这样吧!)

4 个答案:

答案 0 :(得分:11)

虽然@pault的回答解决了您的问题,但我认为它不是超级可读的。 如果只有几个变量,则python的口头禅规定了一种简单明了的方式:

if len(x) == 1:
  f(x)
elif len(y) == 1:
  f(y)
elif len(z) == 1:
  f(z)

否则,如果您有一个列表,则for循环是可读且高效的:

for l in ls:
    if len(l) == 1:
        f(l)
        break

答案 1 :(得分:9)

您可以在此处使用next从符合您条件的选项列表中选择第一项:

value = next((item for item in [x, y, z] if len(item)==1), None)
if value is not None:
    ...

next()的第二个参数是默认值,如果没有值符合您的条件。

答案 2 :(得分:4)

您描述的内容在itertools recipes中有一个称为first_true的常规实现。

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

示例

value = first_true([x, y, z], pred=lambda x: len(x) == 1)

if value:
    ...

答案 3 :(得分:1)

一个小的清单理解就足够了:

passed = [i for i in (x, y, z, xx, yy) if len(i) == 1]
if passed:
     # ... use the ones that passed, or 'passed[0]' for the first item
相关问题