suits = ["h", "c", "d", "s"]
noclubs = list(set(suits) - set(["c"]))
# note no order guarantee, the following is the result here:
# noclubs -> ['h', 's', 'd']
x = ['a', 'b', 'c', 'd']
%%timeit
y = x[:] # fastest way to copy
y.remove('c')
1000000 loops, best of 3: 203 ns per loop
%%timeit
y = list(x) # not as fast copy
y.remove('c')
1000000 loops, best of 3: 274 ns per loop
%%timeit
y = [n for n in x if n != 'c'] # list comprehension
1000000 loops, best of 3: 362 ns per loop
%%timeit
i = x.index('c')
y = x[:i] + x[i + 1:]
1000000 loops, best of 3: 375 ns per loop
def without(iterable, remove_indices):
"""
Returns an iterable for a collection or iterable, which returns all items except the specified indices.
"""
if not hasattr(remove_indices, '__iter__'):
remove_indices = {remove_indices}
else:
remove_indices = set(remove_indices)
for k, item in enumerate(iterable):
if k in remove_indices:
continue
yield item
用法:
li = list(range(5))
without(li, 3)
# <generator object without at 0x7f6343b7c150>
list(without(li, (0, 2)))
# [1, 3, 4]
list(without(li, 3))
# [0, 1, 2, 4]