Python如何将列表子项的数字替换为另一列表对应索引的字符串
问题原因分析
- Python中字符串属于不可变对象,
str.replace()方法不会修改原字符串,只会返回替换后的新字符串,原代码没有接收这个返回值,替换操作本质没有生效。 - 所有替换逻辑执行完成后,没有把最终生成的新字符串赋值回原二维列表的对应位置,所以原列表始终没有改动。
- 额外注意:
max是Python内置的求最大值函数名,不建议用作自定义变量名,会覆盖内置功能,建议换成其他语义更明确的变量名。
修正后的代码
content_list= ['abstract', 'bow', 'button', 'chiffon', 'collar', 'cotton', 'crepe', 'crochet', 'crop', 'embroidered', 'floral', 'floralprint', 'knit', 'lace', 'longsleeve', 'peasant', 'pink', 'pintuck', 'plaid', 'pleated', 'polkadot', 'printed', 'red', 'ruffle', 'sheer', 'shirt', 'sleeve', 'sleeveless', 'split', 'striped', 'summer', 'trim', 'tunic', 'v-neck', 'woven', ''] # 替换原变量名max为data,避免覆盖内置函数 data = [['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '24'],['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '19,15,24']] for item in data: num_str = item[1] # 拆分数字后逐个转索引取对应字符串,最后用逗号拼接 replace_result = [content_list[int(num)] for num in num_str.split(',')] # 把拼接完成的字符串赋值回原位置 item[1] = ','.join(replace_result) print(data)
运行输出
[['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', 'sheer'], ['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', 'pleated,peasant,sheer']]
内容的提问来源于stack exchange,提问作者SoulD82
相关产品推荐
相关产品推荐

