2015-07-01 55 views
1

我有列表unicode的列表。现在我需要将它转换为列表字符串列表。我怎样才能做到这一点?将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 

不同的方法是受欢迎的。

+2

?你应该**总是**提及带有Unicode问题的Python版本,因为在Python 3中处理Unicode的方式与在Python 2中处理Unicode的方式完全不同。 –

+0

@ PM2Ring我明白了。是的,我正在使用Python版本2. – KevinOelen

回答

6

这将返回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提到的,你也可以使用s.encode('ascii', 'ignore'),如果你想忽略unicode字符串不能转换为ascii

获取我们使用的每个列表。 for list in listoflist

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

然后转换成我们使用s.encode('ascii')

+0

这种方式就像一种魅力!谢谢:) – KevinOelen

+0

@KevinOelen:另外,如果你想忽略不能转换为ASCII的Unicode字符,你可以'x.encode'('ascii','ignore')'。有关更多详细信息,请参阅[str.encode]的文档(https://docs.python.org/2/library/stdtypes.html#str.encode)。 –

1

如果你想使你的代码可以理解的,你使用Python 2要这样做

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

这更容易理解。但似乎通过列表迭代是更节省时间的方式。谢谢btw。 – KevinOelen