Moving list entries from one list to another
Alex Martelli
aleax at aleax.it
Sun Jul 14 04:23:32 EDT 2002
JB wrote:
>> I bet you
>> can do better by exploiting the specifics of this case!-)
>
> Well, I can use the fact that I know the maximal sorting key
> in advance. So I can append sentinel entries to both lists
> and this makes things much easier.
Yes. While this may not be the optimal solution to your
actual problem (as I notice the thread is now exploring
quite different architectures), it's getting better as a
solution to the problem you originally expressed about
"moving list entries", as per subject. Untested code
below, but getting a bit more readable, I hope...:
au = [None] * 2
def prepare(au, alist, idx):
alist.append(sentinel)
it = iter(alist)
au[idx] = [ it.next(), idx, it.next, [] ]
prepare(au, list1, 0)
prepare(au, list2, 1)
# naming the items of au's items helps readability:
ITEM, INDX, ITER, LIST = range(4)
# writing complicated expressions as functions also helps:
def moredata(au):
return au[0][ITEM} != sentinel or au[1][ITEM} != sentinel
while moredata(au):
m = min(au)
i = m[INDX]
if i and f(m[ITEM]): i = 0
au[i][LIST].append(m[ITEM])
m[ITEM] = m[ITER]()
# now, both lists are exhausted, so just copy the results back
list1[:] = au[0][LIST]
list2[:] = au[1][LIST]
sentinel is any value > max(max(list1), max(list2)).
Alex
More information about the Python-list
mailing list