我如何删除''在嵌套列表中的项目?
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]]
我如何完成这项任务?
答案 0 :(得分:6)
这并不是真正删除引号。这会使用int
function将str
转换为int
s,使用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 :(得分: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]]
>>>