我应该如何编写这个字符串前缀检查,使其符合Python惯用法?

1 投票
4 回答
2020 浏览
提问于 2025-04-15 21:20

我有几个物品的列表:

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

我想创建一个新的列表,叫做 special_smoothies,这个列表里的元素是 smoothies 中那些以 specials 中的元素开头的东西。不过,如果 specials 是空的,那么 special_smoothies 就应该和 smoothies 一模一样。

有没有什么简单的 Python 方法可以做到这一点?有没有办法在不单独检查 specials 是否为空的情况下实现?

4 个回答

1

str.startswith() 这个函数可以接受一个元组作为参数:

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

因为你希望空的特殊情况和非空的自然情况表现得不一样,所以你需要特别处理一下:

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

换句话说,你希望空的特殊情况表现为“所有的冰沙都是特殊的”,而自然情况下的表现则是“没有冰沙是特殊的”,因为在这种情况下没有任何冰沙是以特殊前缀开头的(因为根本就没有这样的前缀)。所以,不管你用什么方式(比如 if/else 语句),你都需要在代码中处理这个特殊的、不规则的情况,以符合你想要的语义。

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[:]

撰写回答