Python编码列表 'list'对象没有属性 'encode'

标签 python encode

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

最佳答案

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

关于Python编码列表 'list'对象没有属性 'encode',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22231108/

相关文章:

python计算列表中的项目并保持它们的出现顺序

python - django.core.exceptions.ImproperlyConfigured : Set the DATABASE_URL environment variable

python - 防止改变实例变量

Java Date 转换为 String 并返回 Date,相等性检查失败

python 和 PEP 440 - 这个关于 PEP440 的警告有多严重?

python - 提高python中的插入速度

javascript - 如何简单地编码和解码字符串变量

java - 在 jsp 和 struts 中的查询字符串中传递值

c++ - 保留字典顺序的原始类型的字符串编码

string - 如何解码 unicode 字符串 Python