替换Python列表中元素的值

时间:2020-06-14 15:03:40

标签: python python-3.x list

我有一个随机列表;

newList = [2,44,28,32,46,31]

我有一个必须采用这种方式的随机值;

{1:8,2:7,3:6,4:5,5:4,6:3,7:2,8:1}

因此,如果列表中的值为 4 ,则需要替换为 5
如果列表中的值为 2 ,则必须将其替换为 7

当我尝试此代码时:

newList1 = list(map(int, newList))
nnList = []
for i in newList1:
    i = str(i).split(',')
    for y in list(map(str, i)):
        for n in y:
            print(n)
            if n == '1':
                n = 8
            elif n == '2':
                n = 7
            elif n == '6':
                n = 3
            elif n == '3':
                n = 6
            elif n == '4':
                n = 5
            elif n == '5':
                n = 4
            elif n == '7':
                n = 2
            elif n == '8':
                n = 1
            nnList.append(n)
print(nnList)

运行此代码时,我得到以下输出: [7、5、5、7、1、6、7、5、3、6、8]
但是我需要这样: [7,55,71,67,53,68]

我该怎么办?

4 个答案:

答案 0 :(得分:1)

这是您可以做的:

newList = [2, 44, 28, 32, 46, 31]

d = {1:8, 2:7, 3:6, 4:5, 5:4, 6:3, 7:2, 8:1}

l = [int(''.join([str(d[int(g)]) for g in str(n)])) for n in newList]

print(l)

输出:

[7, 55, 71, 67, 53, 68]

答案 1 :(得分:0)

简单的答案是:您需要将一个数字的新数字合并为一个值,然后再将其添加到列表中。

更长的答案是您进行了太多的转化。您无需将整个int值列表转换为单个字符串,并且newList已经是int值列表;您不需要构建newList1

nnList = []
for i in newList:
    newNum = int(''.join(str(9-int(x)) for x in str(i)))
    nnList.append(newNum)

答案 2 :(得分:0)

使用if elselooping的更基本的方法可以是

l1= [2, 44, 28, 32, 46, 31]
dict1={1:8, 2:7, 3:6, 4:5, 5:4, 6:3, 7:2, 8:1}
l2=[]
for n,i in enumerate(l1):
    str1=str(i)
    if len(str1)>1:
        str2=""

        for j in str1:

            if int(j) in dict1:
                str2+=str(dict1[int(j)])

                l1[n]=int(str2)
    else:
        if i in dict1:
            l1[n]=dict1[i]
print(l1)

输出:

[7, 55, 71, 67, 53, 68]

答案 3 :(得分:-1)

newlist = [2, 44, 28, 32, 46, 31]
repl = {1:8, 2:7, 3:6, 4:5, 5:4, 6:3, 7:2, 8:1}

for i, el in enumerate(newlist):
    newlist[i] = repl.get(el, newlist[i])

print(newlist)

repl.get(el, newlist[1])的意思是:尝试在el字典中找到repl,如果不在字典中,请改用newlist[i](原始值),从而替换价值本身。