lists - append - unique and sorted

R

rhXX

hi,

can i append a item to a list using criterias:

- UNIQUE - if there already exist don't append

and/or

- SORTED - INSERT in the correct place using some criteria?

tks in advance
 
D

Diez B. Roggisch

rhXX said:
hi,

can i append a item to a list using criterias:

- UNIQUE - if there already exist don't append

- SORTED - INSERT in the correct place using some criteria?

Both can be accomplished using the bisect-module. It will give you the
leftmost/rightmost insertion point for a given item and a list, and then
you have to see if it is contained in between (or something along these
lines, I hope you get the gist of it)

Diez
 
N

Neil Cerutti

hi,

can i append a item to a list using criterias:

- UNIQUE - if there already exist don't append

Consult the Python Docs about sets.
and/or

- SORTED - INSERT in the correct place using some criteria?

Consult the Python Docs about the heapq module.
 
J

Josiah Carlson

Neil said:
Consult the Python Docs about the heapq module.

Heaps (as produced by heapq) are not sorted. This will not produce
correct results unless one then pops everything and de-dupes the output.

As Diez has already said, 'use the bisect module' .

- Josiah
 
N

Neil Cerutti

Heaps (as produced by heapq) are not sorted. This will not
produce correct results unless one then pops everything and
de-dupes the output.

i agree that using bisect and inserting manually clearly meets
the stated requirements, while there isn't enough information to
know if a heapq will meet his requirements.

Thanks for the correction.
 
D

Dan Bishop

hi,

can i append a item to a list using criterias:

- UNIQUE - if there already exist don't append

and/or

- SORTED - INSERT in the correct place using some criteria?

tks in advance

If you don't need the list to be sorted until you're done building it,
you can just use:

lst = sorted(set(lst))
 
T

Terry Reedy

| If you don't need the list to be sorted until you're done building it,
| you can just use:
|
| lst = sorted(set(lst))

?? looks same as
lst.sort()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top