首页 > 解决方案 > 用另一个列表中的字符串替换列表的元素

问题描述

所以我写了这个,但它并没有完成我想做的事情。基本上,我想用 content_list 列表中该索引处的任何单词替换第二个索引中的数字。

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=[['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '24'],['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '19,15,24']]

for l in max:
  e=l[1]
  f=e.split(",")
  for s in f:
    intt=int(s)
    rep=content_list[intt]
    #print(rep)
    e.replace(s,rep)
    #print(z)

print(max)

这是我得到的输出:

[['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '24'], ['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '19,15,24']]

但这就是我想要的:

[['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', 'sheer'], ['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', 'pleated,peasant,sheer']]

标签: pythonreplace

解决方案


首先,max 是一个内置函数,我强烈建议您检查如何为将来的变量命名,它可能会给您带来一些大问题:)。你也可以像这样蛮力地离开这里:

arr = [
    ['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '24'],
    ['Img/img/Sheer_Pleated-Front_Blouse/img_00000001.jpg', '19,15,24'],
]

for inner in arr:
    indexes=inner[1]
    inner[1] = ""
    for number in indexes.split(","):
        inner[1] += content_list[int(number)]
    print(inner)

推荐阅读