python - 用另一个列表中的字符串替换列表的元素
问题描述
所以我写了这个,但它并没有完成我想做的事情。基本上,我想用 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']]
解决方案
首先,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)
推荐阅读
- swift - 执行上下文菜单操作时如何从 TableViewCell 中获取数组的索引
- c# - 如何修复奇怪的智能感知着色(VS 2019)
- python - 覆盖新生成文件的内容
- mysql - MySQL - 将多个 JSON 值合并为一个带有总和的 JSON
- amazon-web-services - CloudWatch Insights 查询 Lambda 中的错误日志
- javascript - 如何使用 ESLint 自定义规则分析 JS 文字/标识符
- typescript - 打字稿在速记构造函数中创建对象
- javascript - 为名字和姓氏创建一个正则表达式
- css - css溢出魔法有什么魔力
- netlogo - 如何迫使海龟只在半个世界移动?