【问题标题】:Convert unicode to list of tuples将 unicode 转换为元组列表
【发布时间】:2017-05-08 11:37:54
【问题描述】:

我有 Unicode :-

x = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]] <type 'unicode'>

print type(x)
<type 'unicode'>

我需要将其转换为像 [('customer', '=', 1),('parent_id', '=', False)] 这样的元组列表

请帮帮我

【问题讨论】:

  • 您在上面发布的代码无法复制... (repl.it/HmBa/0)。它打印&lt;type 'list'&gt;
  • 我有一个“x”,它是一个 unicode 字符串

标签: python list unicode tuples


【解决方案1】:

这对你有用吗?

my_uni_list = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]
result = [tuple(x) for x in my_uni_list]

【讨论】:

  • @Hoodiee 你说的key是什么意思?
【解决方案2】:

如果您使用的是 python 3.x 并使用 tuple(),则只需 iterate

>>> L = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]] <type 'unicode'>
>>> [tuple(i) for i in L]
[('customer', '=', 1), ('parent_id', '=', False), ('user_id', '=', 1059)]

【讨论】:

  • tuple(i) ... 因为OP想要元组
  • 我有 unicode,需要转换为元组列表
【解决方案3】:

我猜你的意思是:

>>> x = u"[[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]"
>>> print type(x)
<type 'unicode'>

您可以使用eval(x)x 转换为list

>>> l = eval(x)
>>> print type(l)
<type 'list'>

【讨论】:

    【解决方案4】:
    >>> x = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]
    >>> y = map(lambda t: tuple(t),x)
    >>> y
    [(u'customer', u'=', 1), (u'parent_id', u'=', False), (u'user_id', u'=', 1059)]
    

    【讨论】:

      【解决方案5】:

      Python 2:

      >>> x = u"[[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]"
      >>> type(x)
      <type 'unicode'>
      >>> y=[tuple(t) for t in eval(x)]
      >>> y
      [(u'customer', u'=', 1), (u'parent_id', u'=', False), (u'user_id', u'=', 1059)]
      >>> type(y)
      <type 'list'>
      >>> type(y[0])
      <type 'tuple'>
      >>>
      
      >>> map(lambda t: tuple(t),eval(x))
      [(u'customer', u'=', 1), (u'parent_id', u'=', False), (u'user_id', u'=', 1059)]
      >>>
      

      Python 3:

      >>> x = u"[[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]"
      >>> type(x)
      <class 'str'>
      >>> [tuple(t) for t in eval(x)]
      [('customer', '=', 1), ('parent_id', '=', False), ('user_id', '=', 1059)]
      >>>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-13
        • 2016-09-28
        • 1970-01-01
        • 1970-01-01
        • 2018-07-20
        • 2012-06-05
        相关资源
        最近更新 更多