开发者

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

开发者 https://www.devze.com 2022-12-18 16:43 出处:网络
I have a list in python and I\'d like to iterate through it, and selectively co开发者_如何学Cnstruct a list that contains all the elements except the current k\'th element. one way I can do it is this

I have a list in python and I'd like to iterate through it, and selectively co开发者_如何学Cnstruct 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.


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

Is this what you want?


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=[('a', 1), ('b', 2), ('c', 3)]
k=1
l_without_num=l[:]   # or list(l) if you prefer
l_without_num.pop(k)


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


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

lol


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


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 right thing to do, but it's short. :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消