简体   繁体   中英

how to remove specific item words in list python?

color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

i want to remove color [0,4,5] so the output will be :

color ['green', 'White', 'Black']

what should I write?

You can use a list comprehension along with enumerate :

colors = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
indices = [0, 4, 5]
indices_set = set(indices)
filtered = [color for i, color in enumerate(colors) if i not in indices_set]
print(filtered) # ['Green', 'White', 'Black']

You'll have to subtract the position of the element you want to remove since every time you remove an element the length of the list is reduced giving other elements to the given positions,

color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color.pop(0)
color.pop(4-1)
color.pop(5-2)
print(color)

Shortest code for your goal. The print statements are to show it works.

color  = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
remove = [0,4,5]

remove.reverse()

for x in remove:
                print(x)
                color.pop(x)
print(color)

If the numbers in the removal list is changed (eg [0,5,4]) you can sort first:

remove.sort(reverse=True)
[color.pop(x) for x in remove]
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

list(map(color.pop, reversed([0, 4, 5])))

print(color)
['Green', 'White', 'Black']

Note : This is essentially the same answer as @Aplet123, but with a few additional details.

  1. Concise (for your specific case):
[v for i, v in enumerate(colors) if i not in {0, 4, 5}]
  1. More general:
def drop(lst, to_drop):
    drop_idx = frozenset(to_drop)
    return [v for i, v in enumerate(lst) if i not in drop_idx]
  1. Speed test:
colors = list(np.random.uniform(size=1_000_000))
to_drop = list(np.random.choice(np.arange(len(colors)), replace=False, size=10_000))

%timeit drop(colors, to_drop)
# 68.4 ms ± 233 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
inc =[0,4,5]
fil=list(set(color)-set([color[x] for x in inc ]))
print(fil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM