【问题标题】:What is the simplest way to remove unicode 'u' from a list从列表中删除 unicode 'u' 的最简单方法是什么
【发布时间】:2017-12-25 16:07:02
【问题描述】:

我有一个这样的列表

d=[{u'Length': u'2.96m', u'Width': u'1.44m', u'height': u'0.38m'},
{u'Length': u'3.8m', u'Width': u'0.65m', u'height': u'9.3m'},
{u'Length': u'0.62m', u'Width': u'2.9m', u'height': u'3.5m'}]

我想要一种简单的方法来从此列表中删除 unicode 'u' 以创建一个新列表。这里的“简单方法”是在不导入外部模块或将其保存在外部文件中的情况下删除 unicode。

这是我尝试过的五种方法

def to_utf8(d):
    if type(d) is dict:
        result = {}
        for key, value in d.items():
            result[to_utf8(key)] = to_utf8(value)
    elif type(d) is unicode:
        return d.encode('utf8')
    else:
        return d


#these three returns AttributeError: 'list' object has no attribute 'encode'
d.encode('utf-8')
d.encode('ascii')
d.encode("ascii","replace")

#output the same
to_utf8(d)
print str(d)

前三个回报

AttributeError: 'list' 对象没有属性 'encode'

最后两个打印相同的结果。我应该如何删除 unicode 'u'?

【问题讨论】:

  • 使用 str() 函数将其转换为字符串。
  • @JayParikh 尝试了一些工作
  • @Eka 它有效。看我的回答。

标签: python list dictionary unicode


【解决方案1】:

这样怎么样,迭代列表并对字典中的每个键、值进行编码。

converted = [{ str(key): str(value)
                for key, value in array.items() 
            } for array in d]

print (converted)

【讨论】:

  • 在 Python 2 中,str(...) 可能比 .encode('utf-8') 更好,因为unicodestr 不是同一类型。
  • 这个答案首先使用encode("utf-8")。而这个答案的优势必须是列表理解。 str 必须从接受的答案中借用。我认为encode("utf-8").decode("ascii") 揭示了 Python2 中字符串和字节之间的关系。
  • 混淆了,2或3没有指定。
【解决方案2】:

这是最简单的解决方案

d=[{u'Length': u'2.96m', u'Width': u'1.44m', u'height': u'0.38m'},
{u'Length': u'3.8m', u'Width': u'0.65m', u'height': u'9.3m'},
{u'Length': u'0.62m', u'Width': u'2.9m', u'height': u'3.5m'}]

def to_utf8(d):
    final = []
    for item in d:
        if type(item) is dict:
            result = {}
            for key, value in item.items():
                result[str(key)] = str(value)
            final.append(result)
    return final

print to_utf8(d)    

【讨论】:

【解决方案3】:

您应该先将它们编码为字节,然后将它们解码为 ascii 字符串。

l = list()

for item in d:
    temp = dict()
    for key, value in item.items():
        temp[key.encode("utf-8").decode("ascii")] = value.encode("utf-8").decode("ascii")
    l.append(temp)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-11
    • 2012-11-27
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多