将Unicode列表转换为列表字符串

2024-05-29 01:52:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表unicode。现在我需要把它转换成列表字符串列表。我该怎么做?

listoflist = [
    [
        u'keep', u'see', u'recover', u'try', u'cry', u'say', u'seem',
        u'come', u'saw', u'have', u'be', u'begin', u'fell', u'wait',
        u'come', u'wait', u'be', u'retire', u'be'
    ],
    [
        u'make', u'let', u'forget', u'forgive', u'punish', u'take', u'be',
        u'take', u'forget', u'come', u'think', u'say', u'be', u'be', u'say',
        u'think', u'jump', u'poke', u'come', u'be', u'have', u'try', u'come',
        u'turn', u'approach', u'be', u'meet', u'try', u'run', u'boast',
        u'bring', u'satisfy', u'use', u'be', u'leave', u'be', u'do', u'say',
        u'bristle'
    ]
]

我试图使用ast

import ast
d = []
for i in range(0,50):
    d.append([item.encode('ascii') for item in ast.literal_eval(listoflist)])

但我得到了以下错误。

    raise ValueError('malformed string')
ValueError: malformed string

欢迎采用不同的方法。


Tags: in列表forhavebeastitemsay
2条回答

这将返回d作为带有ascii字符串而不是unicode的数组数组。

# Iterate through each list in listoflist
# Then iterate through each unicode string in listoflist

d = [[s.encode('ascii') for s in list] for list in listoflist]

正如@pm-2ring所提到的,如果您想忽略不能转换为asciiunicode字符串,也可以使用s.encode('ascii', 'ignore')

得到我们使用的每个列表。for list in listoflist

获取我们使用的每个unicode字符串。for s in list

然后使用s.encode('ascii')来转换

如果你想让你的代码更容易理解,就这样做

for l in listoflist:
    d_temp = []
    for s in l:
        d_temp.append(s.encode('ascii'))
    d.append(d_temp)

相关问题 更多 >

    热门问题