Python List Rearrange The Elements In A Required Order
My main list has 44 names as elements. I want to rearrange them in a specific order. I am giving here an example. Note that elements in my actual list are some technical names. No
Solution 1:
You can have a dictionary to use as your sorting key:
sort_keys = {
'one': 1,
'two': 2,
'three': 3,
'ten': 10,
'twenty': 20,
}
main_list = ['twenty', 'one', 'three', 'ten', 'two']
main_list.sort(key=lambda i: sort_keys[i])
print(main_list)
Output:
['one', 'two', 'three', 'ten', 'twenty']
Solution 2:
Use something like this (this is just the first Google hit I found for something to convert English representations of numbers to integer values; whatever you use needs to be something that works to convert whatever your actual data is into something sortable): https://pypi.org/project/word2number/
from word2number import w2n
main_list.sort(key=w2n.word_to_num)
Or come up with your own cheesy version as appropriate to your data. Taking your example you could do something like:
number_words = {
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'twenty': 20,
'forty': 40,
'sixty': 60,
}
defword_to_number(word: str) -> int:if word innumber_words:return number_words[word]
# Try chomping each number out of the word.for n innumber_words:if word.endswith(n):
return number_words[n] + word_to_number(word[:-len(n)])
raise ValueError(f"I don't know what number '{word}' is!")
>>> main_list
['one', 'two', 'sixtyfour', 'five', 'six', 'twentyone', 'three', 'four', 'seven', 'eight', 'fortyfour']
>>> sorted(main_list, key=word_to_number)
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'twentyone', 'fortyfour', 'sixtyfour']
Solution 3:
It looks like you want to sort number words in numeric order. But your examples above have poorly-formed words that need fixing, such as twentyone and fortyfour. This is one way you could address it.
from word2number import w2n
main_list = ['one', 'two', 'five', 'six', 'twentyone', 'three', 'four', 'seven', 'eight', 'fortyfour']
VALID = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
TENS = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
renamed = []
for item in main_list:
if item in VALID or item in TENS:
renamed.append(w2n.word_to_num(item))
else:
for num in TENS:
one = item.split(num)[-1]
if one in VALID:
renamed.append(w2n.word_to_num(f'{num}{one}'))
Output
>>>sorted(renamed)
[1, 2, 3, 4, 5, 6, 7, 8, 21, 44]
Post a Comment for "Python List Rearrange The Elements In A Required Order"