Python编码列表“列表”对象没有属性“编码” [英] Python encode list 'list' object has no attribute 'encode'
本文介绍了Python编码列表“列表”对象没有属性“编码”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试从此列表中删除\u0141,我正尝试将其插入数据库中
trying to remove \u0141 from this list which i am trying to insert into my database
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'
推荐答案
大列表中的第一个列表本身包含列表 [ RanRazer的众神之战欧盟#12-\nChallonge\n]
,显然没有 encode()
The first list in your "big list" itself contains a list ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]
, which obviously doesn't have an encode()
method on it.
所以您的算法会发生以下情况:
So what happens in your algorithm is this:
[[somestring.encode, somestring.encode, somestring.encode, [somestring].encode, ...]
您可以使用简单的递归算法:
You could use a simple recursive algorithm though:
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"]]]
当然,这实际上是更通用的递归映射的特例,重构后的映射看起来像这样:
Of course that's actually a special case of a more general recursive map, which, refactored, looks like this:
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'))
这篇关于Python编码列表“列表”对象没有属性“编码”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文