Python encode list'list'对象没有'encode'属性

2024-04-29 10:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试从这个列表中删除我正试图插入数据库的\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'

Tags: ofthein数据库列表forresultsencode
1条回答
网友
1楼 · 发布于 2024-04-29 10:29:21

“大列表”中的第一个列表本身包含一个列表["\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'))

相关问题 更多 >