gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:27:13 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com