[英]How can I remove two elements from a list without a loop?
I have a list我有一个清单
A = [A, B, #, C]
Using a.remove('#')
I can remove the hashtag, but how can I remove both the hashtag and the element before without a loop considering I don't know what the element before the hashtag is?使用
a.remove('#')
我可以删除主题标签,但是考虑到我不知道主题标签之前的元素是什么,如何在没有循环的情况下同时删除主题标签和元素?
Use list.index
to find the position of the hashtag and then use two slices to remove the two elements.使用
list.index
找到 hashtag 的 position ,然后使用两个切片删除这两个元素。
pos = A.index('#')
A = A[:pos - 1] + A[pos + 1:]
A[:pos - 1]
gives everything up to, and not including, the element before the hashtag. A[:pos - 1]
给出了所有内容,但不包括主题标签之前的元素。 A[pos + 1:]
gives everything after the hashtag, then you can combine these two into one list A[pos + 1:]
给出主题标签后的所有内容,然后您可以将这两个组合成一个列表
Alternatively refer to @usr2564301's solution in the comments which removes it in-place (without having to reassign A): A[pos-1:pos+1] = []
, using the same pos
from above或者在评论中参考@usr2564301的解决方案,将其就地删除(无需重新分配A):
A[pos-1:pos+1] = []
,使用上面相同的pos
Note : This assumes that the hashtag is not the first element in the list, otherwise unexpected behavior will occur (refer to @sertsedat's comment below)注意:这假设主题标签不是列表中的第一个元素,否则会发生意外行为(请参阅下面的@sertsedat 评论)
You basically need to know the index of the hashtag.您基本上需要知道主题标签的索引。
A = ['A', 'B', '#', 'C']
hashtag_index = A.index('#')
# here I am removing the hashtag
A.pop(hashtag_index)
# here the element before
if hashtag_index != 0:
A.pop(hashtag_index - 1)
print(A)
# ['A', 'C']
You can also use del in one line (doesn't work when index == 0)您也可以在一行中使用 del (当 index == 0 时不起作用)
del A[hashtag_index - 1:hashtag_index+1]
If you are sure that the element is in the list, you can use index
to get the position in the list and then a couple of pop
to remove the items (assuming that if the hashtag is the first of the list, you just want to remove that):如果您确定该元素在列表中,您可以使用
index
获取列表中的 position ,然后pop
几次删除项目(假设如果主题标签是列表的第一个,您只想删除):
a= ['A', 'B', '#', 'C']
index = a.index('#')
# if the element is not in the list, you will get a ValueError!
a.pop(index)
if index > 0:
a.pop(index-1)
print(a)
# output
['A', 'C']
If you are not sure that the element is in the list, you should then check first if it is, in order to avoid getting a ValueError
:如果您不确定该元素是否在列表中,则应首先检查是否在列表中,以避免出现
ValueError
:
a= ['A', 'B', '#', 'C']
if '#' in a:
index = a.index('#')
a.pop(index)
if index > 0:
a.pop(index-1)
print(a)
# output
['A', 'C']
one way to do it:一种方法:
A = ['A', 'B', '#', 'C']
print(A) #output = ['A', 'B', '#', 'C']
index = A.index("#")
A.pop(index)
A.pop(index-1)
print(A) #output = ['A', 'C']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.