moving items in a list
Cliff Wells
LogiplexSoftware at earthlink.net
Fri Jan 10 17:45:30 EST 2003
On Tue, 2003-01-07 at 13:30, Mark McEahern wrote:
> Below is some code and unit tests to demonstrate how I'm moving items in a
> list. It works, but I'm sure I'll learn a lot by any feedback you care to
> offer.
>
> def move_up(l, m):
> """Move items in m found in l up one position."""
> for i in range(len(l)):
> if i == 0:
> continue
> item = l[i]
> if item not in m:
> continue
> j = i - 1
> swap_with = l[j]
> l[i] = swap_with
> l[j] = item
Here's an alternative. Don't know if it's any better:
def move_up(l, m):
"""Move items in m found in l up one position."""
for i in m:
try:
x = l.index(i)
if x == 0:
continue
l[x-1], l[x] = l[x], l[x-1]
except IndexError:
continue
--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308 (800) 735-0555 x308
More information about the Python-list
mailing list