Frage

Is there an ordered structure in python that interacts when inserting or deleting items? Example: I want to put obj to index 8. So every obj with index greater or equal than 8 will increases by 1.

Example:

Before insert: (Value,Index)=[(a,0),(d,1),(s,2),(t,3),(d,4)]  
After insert (g,2): (Value,Index)=[(a,0),(d,1),(g,2),(s,3),(t,4),(d,5)]

Thank you.

War es hilfreich?

Lösung

All you seem to need here is a list:

>>> l = ['a', 'd', 's', 't', 'd']
>>> l.insert(2, 'g')
>>> l
['a', 'd', 'g', 's', 't', 'd']

The second elements of your tuples are entirely redundant; the information they encode is already represented by the positions of the list elements. enumerate may be useful here:

>>> for index, element in enumerate(l):
...     print index, element
...
0 a
1 d
2 g
3 s
4 t
5 d

Andere Tipps

All you have to do is sorted(sorted, key = lambda i: i[1])

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top