尝试从此列表中删除\ u0141,我尝试将其插入到我的数据库中
results=[['The Squid Legion', '0', u'Banda \u0141ysego', '1', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]], ['Romanian eSports', '1', 'Love', '0', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]]]
results =[[x.encode('ascii', 'ignore') for x in l] for l in results]
我收到此错误:
AttributeError: 'list' object has no attribute 'encode'
答案 0 :(得分:2)
“大列表”中的第一个列表包含一个列表["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]
,它显然没有encode()
方法。
所以你的算法会发生什么:
[[somestring.encode, somestring.encode, somestring.encode, [somestring].encode, ...]
您可以使用简单的递归算法:
def recursive_ascii_encode(lst):
ret = []
for x in lst:
if isinstance(x, basestring): # covers both str and unicode
ret.append(x.encode('ascii', 'ignore'))
else:
ret.append(recursive_ascii_encode(x))
return ret
print recursive_ascii_encode(results)
输出:
[['The Squid Legion', '0', 'Banda ysego', '1', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]], ['Romanian eSports', '1', 'Love', '0', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]]]
当然,这实际上是一个更通用的递归映射的特例,重构的,如下所示:
def recursive_map(lst, fn):
return [recursive_map(x, fn) if isinstance(x, list) else fn(x) for x in lst]
print recursive_map(results, lambda x: x.encode('ascii', 'ignore'))