确定列表中的任意两个字符串在功能上是否以相同的字符开头

2024-05-13 19:39:40 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上,我希望这是False

('click', 'bait', 'carrot', 'juice')

这应该是True,因为每个字符串都以不同的字符开头:

('click', 'bait', 'juice', 'silly')

最接近我得到的是以下,但它看起来不太好

functools.reduce(lambda x, y: (y, x[0] != y[0]), map(operator.itemgetter(0), ('click', 'bait', 'carrot', 'juice')))[1]

它失败是因为它只检查相邻的字符串


Tags: lambda字符串falsetruemapreduce字符operator
3条回答

这将完成以下工作:

l=('click', 'bait', 'carrot', 'juice')
def f(l):
    s=set()
    for i in l:
        if i[0] in s:
            return False
        s.add(i[0])
    return True

集合s由迄今为止看到的第一个字母组成。在每次迭代中,您移动到下一个单词并检查第一个字母是否在s中。如果存在,则返回False。否则,将第一个字母添加到s并继续。循环的优点是,如果第一个字母提前重复,则停止迭代而不继续。从而避免不必要的工作

data = ('click', 'bait', 'carrot', 'juice')

len(set(w[0] for w in data)) == len(data)
# -> False

我想你说的功能性是指没有状态突变

any(n > 1 for n in collections.Counter(s[0] for s in ('click', 'bait', 'carrot', 'juice')).values())

相关问题 更多 >