簡體   English   中英

有沒有更簡短的方法來詢問 2 個變量是否是一個值?

[英]Is there a shorter way to ask if 2 variables are a value?

python 3中有更短的寫法:

if a in ('n', 'm') or b in ('n', 'm'):
    print(a)

我一直在尋找,但沒有找到更短的方法。 我試着把這行寫得更短:

if color1 in ('blue', 'red') or color2 in ('blue', 'red'):

您可以使用set ,特別是set.isdisjoint

if not {color1, color2}.isdisjoint({'blue', 'red'}):
    print(color1)

如果兩個集合不是“不相交的”,那么它們有一個公共元素。 這只能是的情況下,如果在至少一個color1color2屬於{'blue', 'red'}


如果要檢查它們屬於{'blue', 'red'} ,請使用set.issubset或其語法糖<=

if {color1, color2} <= {'blue', 'red'}:
    print(color1)

你可以寫

if any(color in ('blue', 'red') for color in (color1, color2)):

如果您有 3 個或更多變量,將會受益。 如果只有 2 個,您的變體看起來不錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM