Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的简单if语句,测试相互排斥性_Python - Fatal编程技术网

Python中的简单if语句,测试相互排斥性

Python中的简单if语句,测试相互排斥性,python,Python,我正在用python做一些事情,但我还不太习惯 这就是我希望代码执行的操作(伪代码): 第一部分是正确的(如果列表中的x或列表中的y),但我不知道在那之后写什么。部分,而不是x和y部分 我可能会在这里使用集合 if len({x, y}.intersection(your_list)) == 1: # do something 这样做的好处是,它只需要在您的\u列表上迭代一次 示例: examples = [ [1, 2, 3, 4, 5], [2, 3, 4, 5,

我正在用python做一些事情,但我还不太习惯

这就是我希望代码执行的操作(伪代码):


第一部分是正确的(
如果列表中的x或列表中的y
),但我不知道在那之后写什么。
部分,而不是x和y部分

我可能会在这里使用
集合

if len({x, y}.intersection(your_list)) == 1:
    # do something
这样做的好处是,它只需要在您的\u列表上迭代一次

示例

examples = [
    [1, 2, 3, 4, 5],
    [2, 3, 4, 5, 6],
    [100, 101, 102, 103, 104]
]

for example in examples:
    overlap = {1, 5}.intersection(example)
    print 'overlap is', overlap, 'with a length of', len(overlap)

# overlap is set([1, 5]) with a length of 2
# overlap is set([5]) with a length of 1
# overlap is set([]) with a length of 0
使用拼写为“but”的
以及一对括号,您可以使用:

x_in_list = x in list
y_in_list = y in list
if (x_in_list or y_in_list) and not (x_in_list and y_in_list):
    ...
或者,如behzad.nouri所述,使用xor:

if (x in list) ^ (y in list):
    ...
这一段较短,但对于不懂CS的读者来说可能不太容易理解。

独占或表示“一个或另一个,但不是两个”,并且完美地映射了您想要做的事情:

if (x in list) ^ (y in list):
    ...
看起来有点奇怪,因为通常xor只用于按位操作,但在这里可以工作,因为Python会隐式地将
True
False
转换为1和0,使操作符在
if
中按预期工作

但是请注意,括号是必要的,因为异或运算符
^
的优先级高于
中的
(它最常用于按位数学,因此此选择是合理的)。

在负极情况下,此短路版本更好

it
是原始列表的迭代器,我们检查
it
是否在
项中,如果是,我们检查所有其他项是否不在
项中


注意:仅当
项在
lst
中是唯一的时,此操作才有效。您实际上想做什么?我正在遍历一组列表。我希望它仅在列表包含X或Y但不同时包含X或Y的情况下进行计算。使用xor:
(列表中的X)^(列表中的Y)
首先执行if并进行检查,如果要对
列表执行的主要操作是成员资格测试,则应使用集合。谢谢。但是贝扎德。努里的回答为我解决了这个问题。我使用了异或:“
(列表中的x)^(列表中的y)
”@user3685412确实。。。他们都工作。。。但是
(列表中的x)^(列表中的y)
必须扫描
列表
两次,以计算其中一个/orOh OK。那很好。那我一定用你的。列表相当大:)@user3685412注意:如果
x
y
恰好不可损坏,则不能使用此方法……另一方面,您的解决方案需要创建一个临时集。这是一个经典的时间与空间的权衡,但复杂性没有变化。请注意,
True
False
并没有转换为1和0,在非常真实的意义上它们是1和0。
if (x in list) ^ (y in list):
    ...
items, it = {x, y}, (i in items for i in lst)
print(any(it) and not any(it))