gpt4 book ai didi

python - 如何仅在另一个 python 列表中的某个值之后 append 到列表?

转载 作者:行者123 更新时间:2023-12-02 02:03:05 26 4
gpt4 key购买 nike

我有 2 个列表。我只想在达到指定值后追加到新列表。

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value = 'orange'

期望的结果是:

new_list = ['banana', 'grape']

我已经尝试过了,但结果不是我想要的:

for i in old_list:
if i != value:
new_list.append(i)

希望这是有道理的!

最佳答案

使用list.index方法返回i索引,其中value出现在old_list中。然后将 old_list 从索引 i+1 切片到末尾:

old_list = ['apple', 'pear','orange', 'banana', 'grape']
value = 'orange'

i = old_list.index(value)
new_list = old_list[i+1:]

关于python - 如何仅在另一个 python 列表中的某个值之后 append 到列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68748721/

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