![](/img/trans.png)
[英]Splitting a list based on another list that contains the indexes that must be filtered
[英]Is there a prefered way of splitting a list into two based on indexes
例如,如果我有一个包含整数的列表
arr = [1,2,3,4,5,6]
我想根据特定索引将此列表分为两个列表。 如果我指定索引0,1和3,它应该返回包含已删除项目的旧列表,以及仅包含指定项目的新列表。
arr = [1,2,3,4,5,6]
foo(arr, "013"): # returns -> [3,5,6] and [1,2,4]
这是使用生成器函数的一种方法,方法是从输入列表中弹出元素,而这些元素是从函数中产生的。
鉴于列表中的项目在迭代时被删除,因此有必要对索引列表进行反向排序,以使要删除的实际值的索引在输入列表中保持不变,而其值是被删除。
def foo(l, ix):
for i in sorted(list(ix), reverse=True):
yield l.pop(int(i))
通过调用该函数,我们获得已删除的值:
arr = [1,2,3,4,5,6]
list(foo(arr, "013"))[::-1]
# [1, 2, 4]
这些已从原始列表中删除:
print(arr)
# [3, 5, 6]
嗨,您应该看起来像pop()
函数。
使用此功能可直接修改列表。
该代码应如下所示:
def foo( arr, indexes):
res= []
# process list in descending order to not modify order of indexes
for i in sorted(indexes, reverse=True):
res = arr.pop(i)
return res, arr
因此foo(arr, [0,1,3])
返回: [3,5,6], [1,2,4]
创建了一个基于如何同时从列表中删除多个索引的解决方案? 不使用产量。
arr = [1,2,3,4,5,6]
indexes = [0,1,3]
def foo(arr, indexes):
temp = []
for index in sorted(indexes, reverse=True):
temp.append(arr.pop(index))
return arr, temp # returns -> [3, 5, 6] and [4, 2, 1]
这是您需要的:
def foo(arr,idxstr):
out=[] # List which will contain elements according to string idxstr
left=list(arr) # A copy of the main List, which will result to the exceptions of the list out
for index in idxstr: # Iterates through every character in string idxstr
out.append(arr[int(index)])
left.remove(arr[int(index)])
return(out,left)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.