簡體   English   中英

替換 Python 上列表中元素的值

[英]Replace values of elements in a list on Python

我有一個隨機列表;

新列表 = [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)

當我運行這段代碼時,我有這個 output: [7, 5, 5, 7, 1, 6, 7, 5, 3, 6, 8]
但我需要這樣: [7, 55, 71, 67, 53, 68]

我該怎么做?

這是您可以執行的操作:

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)

Output:

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

簡短的回答是:您需要將一個數字的新數字組合成一個值,然后再將其添加到您的列表中。

更長的答案是您進行了太多轉換。 您不需要將整個int值列表轉換為單個字符串,並且newList已經是一個int值列表; 您不需要構建newList1

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

使用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)

output:

[7, 55, 71, 67, 53, 68]
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])意思是:嘗試在repl字典中查找el ,如果不在字典中,則使用newlist[i] (原始值)代替,從而自行替換該值。

暫無
暫無

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

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