python 有效且非破坏性地获取没有第 k 个元素的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2142453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:53:12  来源:igfitidea点击:

getting list without k'th element efficiently and non-destructively

pythonlistcopying

提问by Chris B.

I have a list in python and I'd like to iterate through it, and selectively construct a list that contains all the elements except the current k'th element. one way I can do it is this:

我在 python 中有一个列表,我想遍历它,并有选择地构造一个包含除当前第 k 个元素之外的所有元素的列表。我可以做到的一种方法是:

l = [('a', 1), ('b', 2), ('c', 3)]
for num, elt in enumerate(l):
  # construct list without current element
  l_without_num = copy.deepcopy(l)
  l_without_num.remove(elt)

but this seems inefficient and inelegant. is there an easy way to do it? note I want to get essentially a slice of the original list that excludes the current element. seems like there should be an easier way to do this.

但这似乎效率低下且不优雅。有没有简单的方法来做到这一点?请注意,我想获得排除当前元素的原始列表的一部分。似乎应该有一种更简单的方法来做到这一点。

thank you for your help.

感谢您的帮助。

回答by Chris B.

l = [('a', 1), ('b', 2), ('c', 3)]
k = 1
l_without_num = l[:k] + l[(k + 1):]

Is this what you want?

这是你想要的吗?

回答by vogonistic

It would help if you explained more how you wanted to use it. But you can do the same with list comprehension.

如果您详细解释了您想如何使用它,将会有所帮助。但是你可以对列表理解做同样的事情。

l = [('a', 1), ('b', 2), ('c', 3)]
k = 1
l_without_num = [elt for num, elt in enumerate(l) if not num == k]

This is also more memory efficient to iterate over if you don't have to store it in l_without_num.

如果您不必将其存储在 l_without_num 中,则迭代的内存效率也更高。

回答by John La Rooy

l=[('a', 1), ('b', 2), ('c', 3)]
k=1
l_without_num=l[:]   # or list(l) if you prefer
l_without_num.pop(k)

回答by inspectorG4dget

new = [l[i] for i in range(len(l)) if i != k]

回答by Dan Mantyla

#!/bin/bash
`python -c "'\n'.join(mylist[:])" 2>NULL | sed '/mybadelement/d'`

lol

哈哈

回答by rajivRaja

Using difference operator on sets:

在集合上使用差分运算符:

list(set(l).difference([l[k]])

l=[('a', 1), ('b', 2), ('c', 3)]
list(set(l).difference([l[1]]))
[('a', 1), ('c', 3)]

回答by ephemient

Probably not the most efficient, but the functional programmer in me would probably write this.

可能不是最有效的,但我的函数式程序员可能会写这个。

import operator
from itertools import *
def inits(list):
    for i in range(0, len(list)):
        yield list[:i]
def tails(list):
    for i in range(0, len(list)):
        yield list[i+1:]
def withouts(list):
    return imap(operator.add, inits(list), tails(list))

for elt, without in izip(l, withouts(l)):
    ...


import functools, operator
for elt in l:
    without = filter(functools.partial(operator.ne, elt), l)

I don't think it's the rightthing to do, but it's short. :-)

我不认为这是正确的做法,但它很短。:-)