Python - 字符串和元组比较



如何比较字符串和元组,如果字符串有重复的字母,例如,('PTMP',('P','T','M'))会说raise ValueError(...),但如果元组有一个额外的P,就像('P','T','M','P')一样,答案是有效的?

def whatever(string,tup): 
for j in string: 
if j not in tup: 
raise ValueError('') 
for u in tup: 
if j not in tup: raise ValueError('') 

如果字符串和元组中的字符应该以相同的顺序排列,那么这将对您有用:

if (len(x) == len(y) and all(x[i] == y[i] for i in range(len(x)))):
raise ValueError()
else:
# Be happy

如果您要查找的只是字符串没有比元组更多的任何特定字母,则可以使用Counter减法

from collection import Counter
def can_be_built(s, tup):
if Counter(s) - Counter(tup):
# The string does not use letters the tuple doesn't have
return True
else:
return False

最新更新