Python encode list 'list' object has no attribute 'encode'

前提是你 提交于 2020-01-15 16:48:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!