簡體   English   中英

有沒有一種簡單的方法可以按值刪除列表元素?

[英]Is there a simple way to delete a list element by value?

我想從列表中刪除一個值,如果它存在於列表中(它可能不存在)。

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

以上給出了錯誤:

ValueError: list.index(x): x not in list

所以我必須這樣做:

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print(a)

但是有沒有更簡單的方法來做到這一點?

要刪除列表中第一次出現的元素,只需使用list.remove

>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print(a)
['a', 'c', 'd']

請注意,它不會刪除所有出現的元素。 為此使用列表理解。

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]

通常 Python 會拋出一個異常,如果你告訴它做一些它不能做的事情,所以你必須這樣做:

if c in a:
    a.remove(c)

或者:

try:
    a.remove(c)
except ValueError:
    pass

異常不一定是壞事,只要它是您期望的並且正確處理即可。

你可以做

a=[1,2,3,4]
if 6 in a:
    a.remove(6)

但上面需要在列表中搜索 6 次 2 次,所以嘗試除了會更快

try:
    a.remove(6)
except:
    pass

考慮:

a = [1,2,2,3,4,5]

要取出所有出現的情況,您可以使用 python 中的 filter 函數。 例如,它看起來像:

a = list(filter(lambda x: x!= 2, a))

因此,它將保留a != 2所有元素。

要取出其中一件物品,請使用

a.remove(2)

以下是就地操作的方法(沒有列表理解):

def remove_all(seq, value):
    pos = 0
    for item in seq:
        if item != value:
           seq[pos] = item
           pos += 1
    del seq[pos:]

如果你知道要刪除什么值,這里有一個簡單的方法(無論如何我能想到的最簡單):

a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
    a.remove(1)

你會得到[0, 0, 2, 3, 4]

正如許多其他答案所述, list.remove()將起作用,但如果該項目不在列表中,則會拋出ValueError 使用 python 3.4+,有一個有趣的方法來處理這個問題,使用抑制上下文管理器

from contextlib import suppress
with suppress(ValueError):
    a.remove('b')

另一種可能性是使用集合而不是列表,如果集合適用於您的應用程序。

IE 如果您的數據未排序,並且沒有重復項,則

my_set=set([3,4,2])
my_set.discard(1)

沒有錯誤。

通常,列表只是一個方便的容器,用於存放實際上無序的項目。 有一些問題詢問如何從列表中刪除所有出現的元素。 如果您一開始就不想受騙,那么再次設置一套就很方便了。

my_set.add(3)

不會從上面改變 my_set 。

在一行中:

a.remove('b') if 'b' in a else None

有時它很有用。

更簡單:

if 'b' in a: a.remove('b')

如果您的元素是不同的,那么簡單的集差就可以了。

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]

這個例子很快,將從列表中刪除一個值的所有實例:

a = [1,2,3,1,2,3,4]
while True:
    try:
        a.remove(3)
    except:
        break
print a
>>> [1, 2, 1, 2, 4]

在列表中查找值然后刪除該索引(如果存在)更容易通過使用列表的 remove 方法完成:

>>> a = [1, 2, 3, 4]
>>> try:
...   a.remove(6)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 3, 4]
>>> try:
...   a.remove(3)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 4]

如果你經常這樣做,你可以把它包裝在一個函數中:

def remove_if_exists(L, value):
  try:
    L.remove(value)
  except ValueError:
    pass

通過索引除要刪除的元素之外的所有內容來覆蓋列表

>>> s = [5,4,3,2,1]
>>> s[0:2] + s[3:]
[5, 4, 2, 1]

更普遍,

>>> s = [5,4,3,2,1]
>>> i = s.index(3)
>>> s[:i] + s[i+1:]
[5, 4, 2, 1]

我們也可以使用 .pop:

>>> lst = [23,34,54,45]
>>> remove_element = 23
>>> if remove_element in lst:
...     lst.pop(lst.index(remove_element))
... 
23
>>> lst
[34, 54, 45]
>>> 

使用 for 循環和條件:

def cleaner(seq, value):    
    temp = []                      
    for number in seq:
        if number != value:
            temp.append(number)
    return temp

如果你想刪除一些,但不是全部:

def cleaner(seq, value, occ):
    temp = []
    for number in seq:
        if number == value and occ:
            occ -= 1
            continue
        else:
            temp.append(number)
    return temp

許多答案都涉及創建一個新列表。 這涉及將舊列表中的所有數據復制到新列表(刪除的項目除外)。 如果你的清單很大,你可能負擔不起(或者你不應該想要)。

在這些情況下,就地更改列表要快得多 如果您必須從列表中刪除 1 個以上的元素,這可能會很棘手。 假設您遍歷列表並刪除一個項目,然后列表更改並且標准 for 循環不會考慮到這一點。 循環的結果可能不是您所期望的。

例子:

a = [0, 1, 2, 3, 4, 5]
for i in a:
    a.remove(i)  # Remove all items
print(a)

Out: [1, 3, 5]

一個簡單的解決方案是以相反的順序循環遍歷列表。 在這種情況下,您會得到:

a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
    a.remove(i)  # Remove all items
print(a)

Out: []

然后,如果您只需要刪除具有某些特定值的元素,您可以簡單地在循環中放置一個if statement ,結果:

a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
    if a[i] == 2 or a[i] == 3:  # Remove all items having value 2 or 3.
        a.remove(i)
print(a)

Out: [0, 1, 4, 5]
 list1=[1,2,3,3,4,5,6,1,3,4,5]
 n=int(input('enter  number'))
 while n in list1:
    list1.remove(n)
 print(list1)

例如,我們想從 x 中刪除所有 1。 這就是我將如何去做:

x = [1, 2, 3, 1, 2, 3]

現在,這是我的方法的實際用途:

def Function(List, Unwanted):
    [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
    return List
x = Function(x, 1)
print(x)

這是我在一行中的方法:

[x.remove(1) for Item in range(x.count(1))]
print(x)

兩者都將其作為輸出產生:

[2, 3, 2, 3, 2, 3]

希望這可以幫助。 PS,請注意這是在 3.6.2 版本中編寫的,因此您可能需要針對舊版本對其進行調整。

nums是列表並且c是要刪除的值時:

要刪除列表中第一次出現的c ,只需執行以下操作:

if c in nums:
    nums.remove(c)

要從列表中刪除所有出現的c ,請執行以下操作:

while c in nums:
    nums.remove(c)

添加異常處理將是最佳實踐,但我主要想展示如何從列表中刪除所有出現的元素。

arr = [1, 1, 3, 4, 5, 2, 4, 3]

# to remove first occurence of that element, suppose 3 in this example
arr.remove(3)

# to remove all occurences of that element, again suppose 3
# use something called list comprehension
new_arr = [element for element in arr if element!=3]

# if you want to delete a position use "pop" function, suppose 
# position 4 
# the pop function also returns a value
removed_element = arr.pop(4)

# u can also use "del" to delete a position
del arr[4]

這將從數組sys.argv刪除所有"-v"實例,如果沒有找到實例,則不會抱怨:

while "-v" in sys.argv:
    sys.argv.remove('-v')

您可以在名為speechToText.py的文件中看到正在運行的代碼:

$ python speechToText.py -v
['speechToText.py']

$ python speechToText.py -x
['speechToText.py', '-x']

$ python speechToText.py -v -v
['speechToText.py']

$ python speechToText.py -v -v -x
['speechToText.py', '-x']

也許您的解決方案適用於整數,但它不適用於我的字典。

一方面, remove() 對我不起作用。 但也許它適用於基本類型。 我猜下面的代碼也是從對象列表中刪除項目的方法。

另一方面,“del”也沒有正常工作。 就我而言,使用 python 3.6:當我嘗試使用 'del' 命令從 'for' bucle 中的列表中刪除一個元素時,python 更改了進程中的索引,並且 bucle 在時間之前過早停止。 它僅在您以相反的順序逐個刪除元素時才有效。 通過這種方式,您在瀏覽時不會更改掛起的元素數組索引

然后,我使用了:

c = len(list)-1
for element in (reversed(list)):
    if condition(element):
        del list[c]
    c -= 1
print(list)

其中 'list' 就像 [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]

你也可以使用 enumerate 做更多的 Pythonic:

for i, element in enumerate(reversed(list)):
    if condition(element):
        del list[(i+1)*-1]
print(list)

一些最簡單方法的基准測試:

import random
from copy import copy
sample = random.sample(range(100000), 10000)
remove = random.sample(range(100000), 1000)

%%timeit
sample1 = copy(sample)
remove1 = copy(remove)

for i in reversed(sample1):
    if i in remove1:
        sample1.remove(i)
# 271 ms ± 16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances

%%timeit
sample1 = copy(sample)
remove1 = copy(remove)

filtered = list(filter(lambda x: x not in remove1, sample1))
# 280 ms ± 18.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances

%%timeit
sample1 = copy(sample)
remove1 = copy(remove) 

filtered = [ele for ele in sample1 if ele not in remove1]
# 293 ms ± 72.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances

%%timeit
sample1 = copy(sample)
remove1 = copy(remove) 

for val in remove1:
    if val in sample1:
        sample1.remove(val)
# 558 ms ± 40.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence

%%timeit
sample1 = copy(sample)
remove1 = copy(remove) 

for val in remove1:
    try:
        sample1.remove(val)
    except:
        pass
# 609 ms ± 11.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence

這是一個效率較低的解決方案,但它仍然有效:

a = [ ] // 那是你的列表

b // 你需要刪除的元素

counter = a.count(b)

while counter > 0:
    if b in a:
       a.remove(b)
       counter -= 1

print(a)

這是我的答案,只需使用whilefor

def remove_all(data, value):
    i = j = 0
    while j < len(data):
        if data[j] == value:
            j += 1
            continue
        data[i] = data[j]
        i += 1
        j += 1
    for x in range(j - i):
        data.pop()

語法:lst.remove(x)

lst = ['one', 'two', 'three', 'four', 'two']

lst.remove('two') #it will remove first occurence of 'two' in a given list

del lst[2] #delete item by index value

print(lst)

是。 這是我發現最有用的:

import sys

a = [1, 2, 3, 4]

y = 0

if y < 1:
      a.remove(1)
      print len(a)
else:
    sys.exit()

現在.remove()僅接受一個參數,因此您只能從列表中刪除一個整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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