用新的定制序列号替换索引号

2024-05-23 18:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一个新的定制序列号替换列表项的当前索引号

我有一个不同变量的列表,它们使用下面的代码编制索引

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

感谢您的帮助,并提前表示感谢。你知道吗


Tags: 代码alphanumber列表forindexnanois
1条回答
网友
1楼 · 发布于 2024-05-23 18:41:26

如果我知道你想按特定的顺序替换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)检查它。你知道吗

相关问题 更多 >