我该怎么写这个字符串前缀检查,以便它是惯用的Python?

时间:2010-04-07 14:59:53

标签: python string list

我有几个项目清单:

specials = ['apple', 'banana', 'cherry', ...]
smoothies = ['banana-apple', 'mocha mango', ...]

我想制作一个新列表special_smoothies,其中包含smoothies中以specials中的元素开头的元素。但是,如果specials为空,则special_smoothies应与smoothies相同。

最恐怖的方式是什么?有没有办法在没有单独的条件检查specials是否为空的情况下执行此操作?

4 个答案:

答案 0 :(得分:4)

由于您希望空特价的行为与非空行为的自然限制不同,您需要特殊情况:

if specials:
    specialsmoothies = [x for x in smoothies
                        if any(x.startswith(y) for y in specials)]
else:
    specialsmoothies = list(smoothies)

换句话说,你希望空特价的行为是“所有冰沙都是特殊的”,而自然限制行为就是说在那种情况下“没有冰沙是特别的”,因为它们都没有以其中一个开头特殊的前缀(因为在这种情况下没有这样的前缀)。因此,您需要在代码中创建一个特殊情况,以匹配您在语义中所需的特殊,不规则的大小写。

答案 1 :(得分:3)

如果没有specials的明确检查,有几种方法可以做到这一点。但是不要这样做。

if specials:
  special_smoothies = [x for x in smoothies if any(True for y in specials if x.startswith(y))]
else:
  special_smoothies = smoothies[:]

答案 2 :(得分:1)

str.startswith()接受元组作为参数:

if specials:
    specialsmoothies = [x for x in smoothies if x.startswith(tuple(specials))]
else:
    specialsmoothies = list(smoothies)

答案 3 :(得分:0)

为什么复杂化?我认为这是最具可读性的。 Alex和Ignacio都给出了不避免else条款的充分理由。

special_smoothies = []
if specials:
    for smoothy in smoothies:
        for special in specials:
            if smoothy.startswith(special):
                special_smoothies.append(smoothy)
else:
    special_smoothies = smoothies[:]