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