Ben*_*.Sw 5 python boolean-logic idiomatic logical-operators
我目前正在做一个程序,我已经搜索过但我找不到解决方案; 我的问题是我想要制作一个条件,其中所有选择的变量都不相等,我可以这样做,但只有长行的文本,有更简单的方法吗?到目前为止我的解决方案是:
if A!=B and A!=C and B!=C:
Run Code Online (Sandbox Code Playgroud)
但我想为几组五个变量做这件事,而且很多人都很困惑.我该怎么做才能让它变得更简单?
Sim*_*ser 19
创建一个集合并检查集合中元素的数量是否与传递给它的列表中的变量数量相同:
>>> variables = [a, b, c, d, e]
>>> if len(set(variables)) == len(variables):
... print("All variables are different")
Run Code Online (Sandbox Code Playgroud)
一个集合没有重复元素,因此如果您创建一个集合并且它具有与原始列表中元素数量相同的元素数量,那么您就知道所有元素彼此不同.
如果你可以哈希你的变量(呃,你的变量有意义__hash__
),使用一个集合.
def check_all_unique(li):
unique = set()
for i in li:
if i in unique: return False #hey I've seen you before...
unique.add(i)
return True #nope, saw no one twice.
Run Code Online (Sandbox Code Playgroud)
O(n)最坏的情况.(是的,我知道你也可以len(li) == len(set(li))
,但如果发现匹配,这个变体会提前返回)
如果您不能散列您的值(无论出于何种原因),但可以有意义地比较它们:
def check_all_unique(li):
li.sort()
for i in range(1,len(li)):
if li[i-1] == li[i]: return False
return True
Run Code Online (Sandbox Code Playgroud)
O(nlogn),因为排序.基本上,排序所有内容,并成对比较.如果两件事情是平等的,那么它们应该彼此相邻排序.(如果由于某种原因,你__cmp__
没有对彼此相邻的东西进行排序,1.wut和2.请继续使用下一个方法.)
如果ne
是你唯一的运营商....
import operator
import itertools
li = #a list containing all the variables I must check
if all(operator.ne(*i) for i in itertools.combinations(li,2)):
#do something
Run Code Online (Sandbox Code Playgroud)
我基本上itertools.combinations
用来配对所有变量,然后operator.ne
用来检查不平等.这具有最坏情况下的时间复杂度O(n ^ 2),尽管它仍然应该短路(因为发生器,并且all
是懒惰的).如果你完全确定ne
并且eq
是对立面,你可以使用operator.eq
而any
不是.
附录:文森特写了很多更具可读性版本的itertools
,看起来像变种
import itertools
lst = #a list containing all the variables I must check
if all(a!=b for a,b in itertools.combinations(lst,2)):
#do something
Run Code Online (Sandbox Code Playgroud)
附录2:呃,对于足够大的数据集,可能会使用排序变量heapq
.仍然是O(nlogn)最坏的情况,但O(n)最好的情况.它就像是
import heapq
def check_all_unique(li):
heapq.heapify(li) #O(n), compared to sorting's O(nlogn)
prev = heapq.heappop(li)
for _ in range(len(li)): #O(n)
current = heapq.heappop(li) #O(logn)
if current == prev: return False
prev = current
return True
Run Code Online (Sandbox Code Playgroud)