查找和替换列表中的元素(python)

时间:2010-04-06 01:30:18

标签: python list replace

我必须搜索列表并将所有出现的一个元素替换为另一个元素。到目前为止,我在代码方面的尝试让我无处可去,最好的方法是什么?

例如,假设我的列表具有以下整数

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

我需要用值10替换所有出现的数字1,因此我需要的输出是

>>> a = [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

因此,我的目标是用数字10替换数字1的所有实例。

16 个答案:

答案 0 :(得分:423)

尝试使用list comprehensionternary operator

>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]

答案 1 :(得分:195)

>>> a= [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for n, i in enumerate(a):
...   if i == 1:
...      a[n] = 10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

答案 2 :(得分:26)

列表理解效果很好,并且使用枚举循环可以节省一些内存(b / c操作基本上已经完成)。

还有功能编程。请参阅map的使用情况:

>>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
>>> map(lambda x: x if x != 4 else 'sss', a)
[1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]

答案 3 :(得分:21)

如果要替换多个值,还可以使用字典:

a = [1, 2, 3, 4, 1, 5, 3, 2, 6, 1, 1]
dic = {1:10, 2:20, 3:'foo'}

print([dic.get(n, n) for n in a])

> [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]

答案 4 :(得分:9)

>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> item_to_replace = 1
>>> replacement_value = 6
>>> indices_to_replace = [i for i,x in enumerate(a) if x==item_to_replace]
>>> indices_to_replace
[0, 5, 10]
>>> for i in indices_to_replace:
...     a[i] = replacement_value
... 
>>> a
[6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6]
>>> 

答案 5 :(得分:7)

一个班轮和最快的方法来做到这一点:

[10 if x==1 else x for x in a]

答案 6 :(得分:6)

a = [1,2,3,4,5,1,2,3,4,5,1,12]
for i in range (len(a)):
    if a[i]==2:
        a[i]=123

您可以使用for和while循环;但是,如果你知道内置的枚举函数,那么建议使用枚举。1

答案 7 :(得分:6)

这是一种很酷且可扩展的设计模式,可在O(n)时间内运行...

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

replacements = {
    1: 10,
    2: 20,
    3: 30,
}

a = [replacements.get(x, x) for x in a]

print(a)
# Returns [10, 20, 30, 4, 5, 6, 7, 6, 5, 4, 30, 20, 10]

答案 8 :(得分:2)

以下是Python 2.x中非常直接的方法

 a = [1,2,3,4,5,1,2,3,4,5,1]        #Replacing every 1 with 10
 for i in xrange(len(a)):
   if a[i] == 1:
     a[i] = 10  
 print a

此方法有效。欢迎评论。希望它有所帮助:)

另请尝试了解outis'sdamzam's解决方案的工作原理。列表压缩和lambda函数是有用的工具。

答案 9 :(得分:2)

要在1中轻松替换所有10 a = [1,2,3,4,5,1,2,3,4,5,1]一个人可以使用lambda + map组合,并且“看,妈,没有IF!” :

# This substitutes all '1' with '10' in list 'a' and places result in list 'c':

c = list(map(lambda b: b.replace("1","10"), a))

答案 10 :(得分:1)

你可以在python中使用list comprehension:

def replace_element(YOUR_LIST, set_to=NEW_VALUE):
    return [i
            if SOME_CONDITION
            else NEW_VALUE
            for i in YOUR_LIST]

对于您的情况,您要将所有出现的1替换为10,代码段将如下所示:

def replace_element(YOUR_LIST, set_to=10):
    return [i
            if i != 1  # keeps all elements not equal to one
            else set_to  # replaces 1 with 10
            for i in YOUR_LIST]

答案 11 :(得分:1)

我知道这是一个非常老的问题,并且有无数种方法可以做到。我发现比较简单的一种是使用numpy软件包。

import numpy

arr = numpy.asarray([1, 6, 1, 9, 8])
arr[ arr == 8 ] = 0 # change all occurrences of 8 by 0
print(arr)

答案 12 :(得分:0)

仅查找和替换一项

ur_list = [1,2,1]     # replace the first 1 wiz 11

loc = ur_list.index(1)
ur_list.remove(1)
ur_list.insert(loc, 11)

----------
[11,2,1]

答案 13 :(得分:0)

在长列表和罕见情况下,与其他答案中给出的单步迭代方法相比,使用list.index()的速度快大约3倍。

def list_replace(lst, old=1, new=10):
    start = 0
    try:
        while True:
            i = lst.index(old, start)
            lst[i] = new
            start = i + 1
    except ValueError:
        pass

答案 14 :(得分:0)

for i in range(0, len(lst)):
    lst.insert(i, lst[i])
    lst.remove(lst[i+1])

答案 15 :(得分:0)

这可以通过使用枚举函数轻松完成

代码-

lst=[1,2,3,4,1,6,7,9,10,1,2]
for index,item in enumerate(lst):
    if item==1:
        lst[index]=10 #Replaces the item '1' in list with '10'

print(lst)
相关问题