如何将API返回的编码数组通过字典映射转换为字符串列表?
解决编码到字符串的映射问题(替代报错的map+replace方案)
嘿,这个问题我之前踩过坑!你用map结合replace的思路完全走偏啦——replace是用来替换字符串中的特定子串的,根本不是用来做键值对映射的工具,这就是你一直报错的原因。
咱们直接用字典的键值查找来解决,这才是最直接高效的方式,分两种常见语言给你示例:
JavaScript 实现
// 你的原始编码数组 const OutNames = ["f1", "c2", "b3"]; // 映射字典 const dictionary = {"f1": "Baseball", "b3" : "Soccer" ,"c2": "Football"}; // 核心映射逻辑:用map遍历每个编码,直接从字典取对应值 const displayList = OutNames.map(code => dictionary[code]); console.log(displayList); // 输出: ["Baseball", "Football", "Soccer"]
如果怕API返回了字典里没有的编码,可以加个默认值兜底:
const displayList = OutNames.map(code => dictionary[code] || "Unknown Sport");
Python 实现
# 你的原始编码数组 OutNames = ["f1", "c2", "b3"] # 映射字典 dictionary = {"f1": "Baseball", "b3" : "Soccer" ,"c2": "Football"} # 用map+lambda的方式 display_list = list(map(lambda code: dictionary[code], OutNames)) # 或者更符合Python风格的列表推导式(推荐) display_list = [dictionary[code] for code in OutNames] print(display_list) # 输出: ['Baseball', 'Football', 'Soccer']
同样,加默认值的话用get方法更安全:
display_list = [dictionary.get(code, "Unknown Sport") for code in OutNames]
这样就能完美生成你需要的展示列表啦,再也不会报错~
内容的提问来源于stack exchange,提问作者user27074
相关产品推荐
相关产品推荐

