如果是X或Y或Z,那么使用*那个*?

8

有没有一种方法可以编写一个If(或等效)语句,可以有许多参数,并且如果其中任何一个满足逻辑,则使用变量?

例如

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的方法,那就这样吧!)

@OlivierMelançon - 哦,说得好。我只是尽快想到了一些东西。实际用例是字符串。(我会编辑的) - BruceWayne
1
是否保证只有一个值的长度为1?否则,您是否总是希望使用符合条件的第一个值,或者还有其他标准? - Triggernometry
1
你尝试过使用多个elif语句吗? - brandonwang
2
这实际上是与从可迭代对象中获取满足条件的第一个项相同的问题。 - Aran-Fey
2
可能是重复的问题:从可迭代对象中获取满足条件的第一个项 - David Zemens
4个回答

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

10
您可以在此处使用next,以从符合条件的选项列表中选择第一项:
value = next((item for item in [x, y, z] if len(item)==1), None)
if value is not None:
    ...
< p > < code > next() 的第二个参数是如果没有符合条件的值,则返回的默认值。 < / p >

我使用value = next((item for item in [x, y, z] if item=="no"), default=None)时出现错误:TypeError: next() takes no keyword arguments - BruceWayne
@BruceWayne,你说得对。我刚刚仔细查看了文档,第二个参数不是关键字参数。尝试使用value = next((item for item in [x, y, z] if item=="no"), None)(删除default=)。 - pault

4
你所描述的有一个通用实现,称为 first_true,在itertools recipes中。
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:
    ...

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接