Issue
Python: I have a 1-D list that has the following structure(each entry is a string of integers separated by space):
vals = ["121",
"121 122",
"122",
"122 124",
"150",
"171",
"49",
"49 122",
"49 122" "124",
"49 122" "516",
"51",
"51 122",
"516",
"8",
"8 122" "516",
"8 124",
"8 171",
"8 49",
"8 49" "124",
"8 49" "516",
"8 51",
"8 51" "122",
"8 516",
"878",
]
But I am looking for a sorted order with respect to each integer in the both row as well as column order, i.e., the expected output is
vals = [
"8",
"8 49",
"8 49 124",
"8 49 516",
"8 51",
"8 51 122",
"49",
"49 122",
"49 122 124",
"49 122 516",
"51",
"51 122",
"121",
"121 122",
"122",
"122 124",
"150",
"171",
"516",
"878",
]
I have tried using the sort()
as well as sorted()
mechanism, but nothing seems to work
sort_len = list1.sort(key = int)
--> This is throwing value error as each list is a string of letters seperated.
I want to sort this list by row value, i.e., the first integer in a row (and in case of same row value, i.e., same first integer then go to the next column)
Solution
The trick is turn each string to integer tuple.
print(sorted(vals, key = lambda y: tuple(int(x) for x in y.split())))
['8', '8 49', '8 49 124', '8 49 516', '8 51', '8 51 122', '8 122 516', '8 124', '8 171', '8 516', '49', '49 122', '49 122 124', '49 122 516', '51', '51 122', '121', '121 122', '122', '122 124', '150', '171', '516', '878']
Answered By - Lior Cohen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.