简体   繁体   English

如何删除列表python中的特定项目词?

[英]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 :我想删除颜色 [0,4,5] 所以输出将是:

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

what should I write?我应该写什么?

You can use a list comprehension along with enumerate :您可以将列表理解与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:如果删除列表中的数字发生更改(例如 [0,5,4]),您可以先排序:

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.注意:这与@Aplet123 的答案基本相同,但有一些额外的细节。

  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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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