我的目标是遍历一个名称列表,并且仅当名称的最后一个字母与下一个名称的第一个字母相同时才返回 True。
class Team(object):
def __init__(self, names):
self.names = names
def __iter__(self):
from collections import Counter
first = Counter(map(lambda n: n[0].lower(), self.names))
last = Counter(map(lambda n: n[-1].lower(), self.names))
diff = last - first
return any(diff.values()) <= 1
def isCoolTeam(team):
return bool(Team(team))
print(isCoolTeam(["Rob",
"Bobby",
"Billy"]))
它应该返回 False,但由于某种原因每个输入都返回 true。
最佳答案
函数 any()
返回 boolean
( True
/False
) 和所有 booleans
小于 或等于 ( <=
) 1
.
这意味着 line
:
return any(diff.values()) <= 1
将总是评估为True
.
关于python - 匹配列表中的第一项和最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897305/