2012-04-25 102 views
-4

在嵌套列表:如何從嵌套列表中刪除連字符?

x = [['0', '-', '3', '2'], ['-', '0', '-', '1', '3']] 

我怎麼刪除連字符?

x = x.replace("-", "") 

給我AttributeError: 'list' object has no attribute 'replace',並

print x.remove("-") 

給我ValueError: list.remove(x): x not in list

+4

Python是實際記錄:http://docs.python.org/library/stdtypes.html#typesseq-mutable – jogojapan 2012-04-25 03:37:30

+0

編輯以更好地解釋我的難題:P – 2012-04-25 03:45:42

回答

1

x是列表的列表。 replace()將替換字符串內的另一個模式字符串。你想要的是從列表中刪除一個項目。 remove()將刪除第一次出現的物品。一個簡單的方法:

for l in x: 
    while ("-" in l): 
     l.remove("-") 

對於更高級的解決方案,請參閱以下內容:Remove all occurrences of a value from a Python list

+0

你真是國王之王!謝謝! – 2012-04-25 03:39:10

+0

不客氣。不過,我傾向於同意@jogojapan,Python的文檔相當廣泛,這是一個簡單的問題。下次嘗試做一些研究。 – 2012-04-25 03:40:29

+0

對不起,我也試過。我也應該包括那個錯誤。 – 2012-04-25 03:46:26