gpt4 book ai didi

python - 循环遍历字符串列表并删除特定列表项 (i) 之后的所有项,其中 i 可以是 a 或 b 或 c

转载 作者:行者123 更新时间:2023-12-03 21:15:48 25 4
gpt4 key购买 nike

在列表中搜索并删除包含在 Audi 或 Mazda 或 Suzuki 之后的所有其他内容。请注意 只有一个 3 个可以在列表中,但 不是 两个或全部。 只有其中之一

第一个场景:if it's Audi,给出一个列表(列表项是随机的):

lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]

预期结果:
new_lst = ["Nissan","Chevrolet"]

场景二: If it's Suzuki .

预期结果
lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru","Suzuki","Mitsubishi"]

new_lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru"]

等等等等

最佳答案

您可以使用 itertools.takewhile创建一个新列表并在适当的点“突破”

>>> from itertools import takewhile
>>> lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]
>>> list(takewhile(lambda x: x != "Audi", lst))
['Nissan', 'Chevrolet']

关于python - 循环遍历字符串列表并删除特定列表项 (i) 之后的所有项,其中 i 可以是 a 或 b 或 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60756373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com