如何最简单地从列表中删除Unicode字符'u'

3

我有一个这样的列表

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)

前三个返回值

属性错误:'list'对象没有'encode'属性

最后两个打印出相同的结果。如何去除Unicode中的'u'?


使用str()函数将其转换为字符串。 - Jay Parikh
@JayParikh 尝试了,但没有成功。 - Eka
@Eka,它有效。请看我的答案。 - Jay Parikh
3个回答

3
如何做呢?迭代列表并对字典中的每个键值进行编码。
converted = [{ str(key): str(value)
                for key, value in array.items() 
            } for array in d]

print (converted)

在Python 2中,unicodestr 不是相同的类型,因此最好使用 str(...) 而不是 .encode('utf-8') - JohanL
首先,这个答案使用了encode("utf-8")。并且这个答案的优点在于列表推导式。同时,这里的str必须借用自已被接受的答案。我认为在Python2中,encode("utf-8").decode("ascii")揭示了字符串与字节之间的关系。 - stamaimer
因为没有指定2或3,所以有些困惑。 - Jiun Bae

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)    

1
不,这不是最简单的方法。在我的看法中,https://dev59.com/tKPia4cB1Zd3GeqP05d6#45206700 的答案更简单。 - JohanL

0

你应该先将它们编码为字节,然后解码为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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接