[英]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 else
和looping
的更基本的方法是,
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.