高效且非破坏性地获取没有第 k 个元素的列表
我在 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)
但这似乎效率低下且不优雅。有简单的方法吗?注意我本质上想获取原始列表的一部分,不包括当前元素。似乎应该有一种更简单的方法来做到这一点。
感谢您的帮助。
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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是你想要的吗?
Is this what you want?
如果您详细解释一下您想如何使用它,将会有所帮助。但是您可以对列表理解执行相同的操作。
如果您不必将其存储在 l_without_num 中,那么迭代的内存效率也会更高。
It would help if you explained more how you wanted to use it. But you can do the same with list comprehension.
This is also more memory efficient to iterate over if you don't have to store it in l_without_num.
哈哈
lol
在集合上使用差分运算符:
Using difference operator on sets:
可能不是最有效的,但我的函数式程序员可能会写这个。
我认为这不是正确的做法,但它很短。 :-)
Probably not the most efficient, but the functional programmer in me would probably write this.
I don't think it's the right thing to do, but it's short. :-)