Python 有没有更好的方法可以根据索引将列表一分为二
例如,如果我有一个包含整数的列表Python 有没有更好的方法可以根据索引将列表一分为二,python,list,indexing,split,Python,List,Indexing,Split,例如,如果我有一个包含整数的列表 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] 这里有一种使用生成器函数的方法,从输入列表中弹出元素,同时从函数中生成元素 鉴于列表中的项目在迭代时被删除,因此有必要对索引列表进行反向排序,以便在删除
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)