You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字典中的数值列表转换为字符串列表?要求不使用map()函数

问题根因

Python 3 中 map() 函数返回的是惰性迭代器对象,不是列表类型,所以你直接赋值后拿到的不是预期的字符串列表,必须显式用list()包裹转换才能得到列表结果。

不使用map()的实现方案
  • 方案1:列表推导式(最推荐)
    写法简洁直观,是Python中处理列表转换的常用写法:
    dictionary = {"first":[1, 2, 3], 
                  "second":[4, 5, 6, 7, 8]}
    
    d = {k: [str(num) for num in v] for k, v in dictionary.items()}
    
    运行后得到的d就完全符合你的预期输出。
  • 方案2:循环遍历追加
    适合转换时需要附加额外处理逻辑的场景,灵活度更高:
    dictionary = {"first":[1, 2, 3], 
                  "second":[4, 5, 6, 7, 8]}
    d = {}
    for key, num_list in dictionary.items():
        temp = []
        for n in num_list:
            temp.append(str(n))
        d[key] = temp
    
原map写法的修正(可选参考)

如果你后续需要用map写法,只要加一层list()转换即可:

d = {k: list(map(str, v)) for k,v in dictionary.items()}

内容的提问来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:15:04