Reputation: 55
I want to get a ordered list with ascending order, but leave out the first element in the original list. But the first for-loop only runs 4 times. After 4 times loop in first for-loop:
lst=[6, 5, 4]
I think the first for-loop should keep running, but it finishes. I don't know why?
Source code below:
#coding: utf-8
lst = [0, 1, 6, 2, 5, 3, 4]
new_lst = [] # the ordered list, [0, 1, 2, 3, 4, 5, 6]
p0 = lst[0] # the first element can be arbitrary
lst.remove(p0)
new_lst.append(p0)
for temp in lst:
lst.remove(temp)
while 1:
for pt in lst:
if temp < pt:
continue
else:
lst.append(temp)
temp = pt
lst.remove(pt)
break
else:
new_lst.append(temp)
break
print("the ordered list:", new_lst)
At last, I only get:
('the ordered list:', [0, 1, 2, 3])
Upvotes: 0
Views: 107
Reputation: 136
If you can use sorted, that's the easiest way to do it. If not, this is my solution:
lst = [0, 1, 6, 2, 5, 3, 4]
new = lst[1:]
for num in range(len(new)-1, 0, -1):
for i in range(num):
if new[i] > new[i+1]:
new[i], new[i+1] = new[i+1], new[i]
new.insert(0, lst[0])
print(new)
Upvotes: 0
Reputation: 24535
To ignore first element in sorting:
newlst = [lst[0]]+sorted(lst[1:])
First element lst[0] has to be enclosed in [ ] to get a list which can be extended using +
with rest of the list (lst[1:]).
Upvotes: 1
Reputation: 459
try new_lst = sorted(lst)
. This sorts a list by integer value (and ascii value if characters are present). This is a much nicer solution for your problem and is way more pythonic.
Upvotes: 0