2014-01-29 131 views
2

如何刪除嵌套列表中的項目?在python中刪除嵌套列表中的項目撇號

c = [['1', '1', '10', '92'], ['262', '56', '238', '142'], ['86', '84', '149', '30'], ['48', '362', '205', '237'], ['8', '33', '96', '336'], ['39', '82', '89', '140'], ['170', '296', '223', '210'], ['16', '40', '65', '50'], ['16', '40', '65', '50']] 

>>> [ ','.join(i[0:][0:]) for i in c] 
['1,1,10,92', '262,56,238,142', '86,84,149,30', '48,362,205,237', '8,33,96,336', '39,82,89,140', '170,296,223,210', '16,40,65,50', '16,40,65,50'] 

不過,我會繼續括號

[[1,1,10,92], [262,56,238,142], [86,84,149,30], [48,362,205,237], [8,33,96,336'] [39,82,89,140], [170,296,223,210], [16,40,65,50], [16,40,65,50]] 

我怎樣才能完成這個任務?

+2

這些引號表示您的子列表的元素是* strings *。你需要把它們變成整數。 – roippi

回答

6

這不是真的刪除引號。它使用int functionstr秒值進行轉換成int S和A list comprehension打造的結果:

In [72]: [map(int, grp) for grp in c] 
Out[72]: 
[[1, 1, 10, 92], 
[262, 56, 238, 142], 
[86, 84, 149, 30], 
[48, 362, 205, 237], 
[8, 33, 96, 336], 
[39, 82, 89, 140], 
[170, 296, 223, 210], 
[16, 40, 65, 50], 
[16, 40, 65, 50]] 
+1

請注意,如果您使用的是Python3,那麼您必須在c3中爲'grp'執行'[list(map(int,grp)),因爲'map()'返回Python3中的地圖對象,而不是列表。 –

3

列表理解可以嵌套下去。所以,你只需要做一個嵌套的將字符串轉換爲整數:

>>> c = [['1', '1', '10', '92'], ['262', '56', '238', '142'], ['86', '84', '149', '30'], ['48', '362', '205', '237'], ['8', '33', '96', '336'], ['39', '82', '89', '140'], ['170', '296', '223', '210'], ['16', '40', '65', '50'], ['16', '40', '65', '50']] 
>>> [[int(y) for y in x] for x in c] 
[[1, 1, 10, 92], [262, 56, 238, 142], [86, 84, 149, 30], [48, 362, 205, 237], [8, 33, 96, 336], [39, 82, 89, 140], [170, 296, 223, 210], [16, 40, 65, 50], [16, 40, 65, 50]] 
>>> 
+0

謝謝大家快速回復,這兩個例子都很有用 – Robert