问题
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]
I am getting this error:
AttributeError: 'list' object has no attribute 'encode'
回答1:
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)
outputs:
[['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'))
来源:https://stackoverflow.com/questions/22231108/python-encode-list-list-object-has-no-attribute-encode