2014-03-06 39 views
0

試圖從該名單中我試圖插入我的數據庫中刪除\ u0141Python的編碼清單「列表」對象有沒有屬性「編碼」

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' 
+4

您的列表至少有3個層次,但您只能迭代2個層次。 –

+1

而你的一些字符串只有2級。 –

+0

每個'l'的最後一個'x'是一個列表。 –

回答

2

「大列表」中的第一個列表本身包含一個列表["\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')) 
相關問題