3

How I can remove '' in items in nested list?

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']

But, I will keep square bracket

[[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]]

how I can accomplish this task?

Robert
  • 651
  • 1
  • 6
  • 18
  • 2
    those quotes denote that the elements of your sublists are *strings*. You need to turn them into integers. – roippi Jan 29 '14 at 21:47

2 Answers2

6

This isn't really removing quotations marks. This uses the int function to convert strs into ints, and a list comprehension to build the result:

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]]
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    Note that if you're using Python3, you'll have to do `[list(map(int, grp)) for grp in c]` since `map()` returns a map object in Python3, not a list. – Adam Smith Jan 29 '14 at 21:47
3

List comprehensions can nest indefinitely. So, you just need to make a nested one that will convert the strings into integers:

>>> 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]]
>>>