-2

I have something like this:-

List = [["a","1"],["b","2"]]

and what I wanna do is keep single letter integers as integers. so output should be like

List =  [["a",1],["b",2]]
hyde
  • 50,653
  • 19
  • 110
  • 158
Aybar Taş
  • 15
  • 1
  • 6

2 Answers2

6

Assuming that you stored that in a list called "data", you can do the following.

new_data = [[k,int(v)] for k,v in data]

Refer below for details:

data =  [["a","1"],["b","2"]]
new_data = [[k,int(v)] for k,v in data]

print new_data

Output:

[['a', 1], ['b', 2]]
Tameem
  • 243
  • 2
  • 18
3

Changed question before rollback: Sort heterogeneous list

It seems that you completely changed your question after people answered the first version. Please don't do that. You could simply ask a new question.

If you want to sort a heterogeneous list, you can provide a custom key which returns a tuple. The first element is 0 for strings and 1 for integers. This way, the strings would appear before the integers. If the object is an integer, the second element is set to -x in order to sort the integers in decreasing order:

def custom_order(x):
    if isinstance(x, int):
        return (1, -x)
    else:
        return (0, x)

print(sorted([1,2,3,4,5,"a","b","c","d"], key=custom_order))
# ['a', 'b', 'c', 'd', 5, 4, 3, 2, 1]

This code should work on Python2 and Python3. It will fail on Python3 if an element is neither a string nor an int.

Original question: convert nested strings to ints

You could use a nested list comprehension with a ternary operator to check if the string looks like an integer:

>>> data = [["a","1"],["b","2"]]
>>> [[int(s) if s.isdecimal() else s for s in l] for l in data]
[['a', 1], ['b', 2]]

As a bonus, it would work in any order and with sub-lists of any size:

>>> data = [["a","1"],["b","2"],["3", "c"], ["4", "5", "d"]]
>>> [[int(s) if s.isdecimal() else s for s in l] for l in data]
[['a', 1], ['b', 2], [3, 'c'], [4, 5, 'd']]
hyde
  • 50,653
  • 19
  • 110
  • 158
Eric Duminil
  • 48,038
  • 8
  • 56
  • 100