如何仅在另一个python列表中的某个值之后追加到列表



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

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

您可以尝试使用布尔值来检查"orange"是否已通过。

试试这个:

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'
checker = False
for i in old_list:
if checker:
new_list.append(i)
if i == value:
checker = True

希望这能帮助你

有很多方法可以做到这一点。在不知道自己尝试了什么的情况下,这里有一种方法:

i = old_list.index('orange')
i = i + 1
while i < len(old_list):
new_list.append(old_list[i])
i = i + 1

找到"orange"的索引,然后循环遍历old_list中的其余值,并将它们附加到new_list中。

使用itertools模块,

from itertools import dropwhile

def takeafter(iterator, value):
itr = dropwhile(lambda x: x != value, iterator)
try:
next(itr)
except StopIteration:
pass
return itr

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'
new_list.extend(takeafter(old_list, value))

dropwhile创建一个迭代器,一旦谓词为true,该迭代器就开始从其输入中生成值。由于我们也不想要第一项,所以在返回迭代器之前,我们使用next提前传递起始值。

您可以生成一个if语句,检查第一个列表是否包含您的"指定值";,然后追加到下一个列表。

如果没有,它将附加到第一个列表中。

例如

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'
if value in old_list:
new_list.append('banana', 'grape')
else:
old_list.append('banana', 'grape')

Haniel

相关内容

最新更新