【问题标题】:Python 2 How to change list of unicode returned by values_list operation to list of stringsPython 2 如何将 values_list 操作返回的 unicode 列表更改为字符串列表
【发布时间】:2013-01-31 12:05:11
【问题描述】:

我执行了这个操作来检索一个查询集:

Name.objects.values_list('name', flat=True)

它会返回这些结果:

[u'accelerate', u'acute', u'bear', u'big']

结果都是 unicode (u')。如何将它们全部删除以获得结果:

['accelerate', 'acute', 'bear', 'big']

【问题讨论】:

    标签: python django django-views django-queryset


    【解决方案1】:

    如果你想用 utf8 编码,你可以这样做:

    definitions_list = [definition.encode("utf8") for definition in definitions.objects.values_list('title', flat=True)]
    

    【讨论】:

      【解决方案2】:

      您可以在所有值上调用 str(注意 map 有点懒,添加了 list() 以立即将其转回可索引对象):

      thingy = list(map(str, [u'accelerate', u'acute', u'bear', u'big']))
      

      或者使用列表推导:

      [str(item) for item in [u'accelerate', u'acute', u'bear', u'big']]
      

      最后,你为什么要明确要求他们是str?添加到 django 模板(如 {{ value }}),u 将消失。

      【讨论】:

      • 如前所述,您可以省略 list() 调用。我这样做没有遇到任何问题。如果您能详细说明为什么会出现问题,我将不胜感激!
      • 嗯,你是对的。刚刚在 py27 和 py34 中尝试过,其中 py27 返回一个 list,py34 返回一个 map 对象。在模板中使用可能没有区别。我将保持原样,因为解释器的输出更加清晰(没有list(),py3 将声明类似<builtins.map at 0x7f016df386a0>)。
      【解决方案3】:

      我认为捷径是使用json.dumps()

      json.dumps(definitions.objects.values_list('title', flat=True))
      

      所以你会得到像json格式的字符串结果

      '["accelerate", "acute", "bear", "big" ...]'
      

      如果你想把它改成python变量,只需使用eval作为函数,这样你的代码就更像这样了

      json_format_string = json.dumps(definitions.objects.values_list('title', flat=True))
      
      my_list = eval(json_format_string)  # ['accelerate', 'acute', 'bear', 'big' ...]
      

      【讨论】:

        【解决方案4】:

        在 python 2.7 中使用不带列表的地图也可以

        list_of_python_strings = map(str, [u'accelerate'])
        

        【讨论】:

          【解决方案5】:

          我用过这个

          my_list = list(map(str, [u'accelerate', u'acute', u'bear', u'big'...]))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-09-18
            • 2017-05-22
            • 1970-01-01
            • 2014-06-29
            • 2010-12-18
            • 2015-09-18
            • 2021-08-21
            • 2015-10-24
            相关资源
            最近更新 更多