将索引号替换为新的自定义序列号



我想用新的自定义序列号替换列表项目的当前索引号

我有一个包含不同变量的列表,它们使用以下代码进行索引

list_a = ["alpha","beta","romeo","nano","charlie"]
for idx, val in enumerate(list_a, start=1):
print("index number for %s is %d" % (val, idx))

这给了我以下结果。

index number for alpha is 1
index number for beta is 2
index number for romeo is 3
index number for nano is 4
index number for charlie is 5    

现在我想用自定义列表替换上述从 1 到 5 的索引号,如下所示

index number for alpha is 1Red
index number for beta is 2Blue
index number for romeo is 3Purple
index number for nano is 4Red
index number for charlie is 5Blue

感谢您的帮助,并提前表示感谢。

如果我知道您想按特定顺序替换list_a的值并且没有逻辑/规则,对吧?

所以你可以用很多方法做到这一点,但如果这样做,你会失去你的约会list_a,所以我会告诉你另外两种解决这个问题的方法,好吗?!

第一种方式

list_a = ["alpha","beta","romeo","nano","charlie"]
cust_list = ['Red', 'Blue', 'Purple', 'Red', 'Blue'] #create a new list
#Create your logical by for
for id_a, id_b, i in zip(list_a, cust_list, range(5)):
cust_list[i] = str(i+1)+id_b
#Make some changes in your code and run it
for idx, val in enumerate(list_a, start=1):
print("index number for %s is %s" % (val, cust_list[idx-1]))

第二种方式通过列表理解

list_a = ["alpha","beta","romeo","nano","charlie"]
cust_list = ['Red', 'Blue', 'Purple', 'Red', 'Blue'] #create a new list
#adding new items by list comprehension
[cust_list.insert(i,str(i+1)+cust_list[i]) for i in range(len(list_a))]
#deleting old items
for i in range(5):
del cust_list[-1]
#Make some changes in your code and run it
for idx, val in enumerate(list_a, start=1):
print("index number for %s is %s" % (val, cust_list[idx-1]))

您的新数据存储在cust_list中,您可以通过print(cust_list)查看。

最新更新