将 Python 列表编码为 UTF-8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16957226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:04:59  来源:igfitidea点击:

Encode Python list to UTF-8

pythonlistencode

提问by Tom

I have a python list that looks like that:

我有一个看起来像这样的python列表:

list = [u'a', u'b', u'c']

Now I want to encode it in UTF-8. Therefore I though I should use:

现在我想用UTF-8编码它。因此,我虽然应该使用:

list = list[0].encode("utf-8")

But print list gives only

但打印列表只给出

a

meaning the first element of the list. Not even a list anymore. What am I doing wrong?

表示列表的第一个元素。连名单都没有了。我究竟做错了什么?

采纳答案by jamylak

>>> items =  [u'a', u'b', u'c']
>>> [x.encode('utf-8') for x in items]
['a', 'b', 'c']

回答by njzk2

list[0]is the first element, not a list. you are reassigning your listvar to a new value, the utf-8 encoding of the first element.

list[0]是第一个元素,而不是列表。您正在将listvar重新分配给一个新值,即第一个元素的 utf-8 编码。

Also, don't name your variables list, as it masks the list()function.

另外,不要命名您的 variables list,因为它会屏蔽list()函数。