簡體   English   中英

如何在沒有循環的情況下從列表中刪除兩個元素?

[英]How can I remove two elements from a list without a loop?

我有一個清單

A = [A, B, #, C]

使用a.remove('#')我可以刪除主題標簽,但是考慮到我不知道主題標簽之前的元素是什么,如何在沒有循環的情況下同時刪除主題標簽和元素?

使用list.index找到 hashtag 的 position ,然后使用兩個切片刪除這兩個元素。

pos = A.index('#')
A = A[:pos - 1] + A[pos + 1:]

A[:pos - 1]給出了所有內容,但不包括主題標簽之前的元素。 A[pos + 1:]給出主題標簽后的所有內容,然后您可以將這兩個組合成一個列表

或者在評論中參考@usr2564301的解決方案,將其就地刪除(無需重新分配A): A[pos-1:pos+1] = [] ,使用上面相同的pos

注意:這假設主題標簽不是列表中的第一個元素,否則會發生意外行為(請參閱下面的@sertsedat 評論)

您基本上需要知道主題標簽的索引。

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

您也可以在一行中使用 del (當 index == 0 時不起作用)

del A[hashtag_index - 1:hashtag_index+1]

如果您確定該元素在列表中,您可以使用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']

如果您不確定該元素是否在列表中,則應首先檢查是否在列表中,以避免出現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']

一種方法:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM