1

I have to convert all string elements of a 2-D list to integers except for the first element. For example, for a list:

result = [['foo', '2', '21', '48'], ['bar', '18', '180', '54']]

I only wish to change the type of the "numbers" in the list to int type (say, '2', '21', '48' in first row).

I have tried using a list comprehension,

result = [int(x) for x in result[i]]
# where i is the traversal variable

but this gives invalid literal for int() with base 10: 'foo' which is precisely what I am trying to avoid.

Any ideas on how to achieve this without creating another copy of the list? I want to reflect the changes back to the original list.

  • Use [slicing](https://stackoverflow.com/questions/509211/understanding-slice-notation) to only get the values you need e.g. to omit the first value in the array use `result[row][1:]` where `row` is the row index. – Mushroomator Mar 21 '22 at 16:07
  • I don't see the requirement _"except the first element"_ reflected in your implementation. – jonrsharpe Mar 21 '22 at 16:07

4 Answers4

3

Perhaps you're looking for str.isdigit:

out = [[int(x) if x.isdigit() else x for x in lst] for lst in result]

Output:

[['foo', 2, 21, 48], ['bar', 18, 180, 54]]
2
result = [int(x) for x in result[1:][i]]

try this

White_Sirilo
  • 264
  • 1
  • 11
  • I did try this previously but I received this error(and it's still there, naturally): `TypeError: 'int' object is not subscriptable.` So, I did not include this in my implementation – a certain wanderer Mar 21 '22 at 16:34
1

You need to use list slicing to ignore the first element in each list. The most concise way of accomplishing this is by using map():

result = [['foo', '2', '21', '48'], ['bar', '18', '180', '54']]

for sublist in result:
    sublist[1:] = map(int, sublist[1:])

# Prints [['foo', 2, 21, 48], ['bar', 18, 180, 54]]
print(result)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
1

If you're confident about all elements after the first one in each sublist being numeric (or you want to enforce that assumption such that an exception will be raised if it's violated), you could do the type conversion based on the index rather than the value, e.g.:

>>> result = [['foo', '2', '21', '48'], ['bar', '18', '180', '54']]
>>> result = [[int(x) if i else x for i, x in enumerate(row)] for row in result]
>>> result
[['foo', 2, 21, 48], ['bar', 18, 180, 54]]
Samwise
  • 68,105
  • 3
  • 30
  • 44