0
Creating a self-numbering ranking list
Can someone offer a solution to this problem? Say I a ranked list: 5. Pineapple 4. Peach 3. Kiwi 2. Apple 1. Banana I then add a new entry to the ranking: 5. Pineapple 4. Peach #. Plum <--new text 3, Kiwi 2. Apple 1. Banana Can I set up the list to automatically reorder as follows? 6. Pineapple 5. Peach 4. Plum 3, Kiwi 2. Apple 1. Banana Thanks!
3 Answers
+ 1
use can use the Slicing indexing in Python to split and append a new element and then join it to create a new list with the new element having a certain index.
Here is the code and I want you to learn from it not just expect answers from the community.
https://www.sololearn.com/compiler-playground/cSka5pKO8H6X
0
Savager
you should try list.insert()
or you can use OOP for more advanced list operations:
https://realpython.com/inherit-JUMP_LINK__&&__python__&&__JUMP_LINK-list/
0
#Savager copy-paste this:
#class inherit from list
class MyList(list):
def __init__(self, li):
super().__init__(v for v in li)
#custom __str__method
def __str__(self):
s = ""
for i, v in enumerate(self):
s+=f'{len(self)-i}. {v}\n'
return s
#custom insert method
def insert(self, i, v):
super().insert(len(self)-i, v)
## TEST ##
fruits = MyList(['Pineapple', 'Peach'])
#custom __str__method
print(fruits)
#built-in list methods
fruits.append('Kiwi')
fruits.extend(['Apple', 'Banana'])
print(fruits)
#custom insert method
fruits.insert(3, 'Plum')
print(fruits)