我对编程还很陌生;我只研究Python几周了.最近,我进行了一次练习,要求我生成一个整数列表,然后在一个单独的列表中手动将数字从最低到最高排序.
I'm fairly new to programming; I've only been studying Python for a few weeks. I've been given an exercise recently that asks me to generate a list of integers, and then manually sort the numbers from lowest to highest in a separate list.
import random unordered = list(range(10)) ordered = [] lowest = 0 i = 0 random.shuffle(unordered) lowest = unordered[0] while i in unordered: if unordered[i] < lowest: lowest = unordered[i] i += 1 if i >= len(unordered): i = 0 ordered.append(lowest) unordered.remove(lowest) lowest = unordered[i] print(ordered)这是我到目前为止的内容,老实说,它根本不起作用.我得到的伪代码是这样的:
This is what I have so far, and to be quite frank, it doesn't work at all. The pseudocode I have been given is this:
- 创建一个空列表来保存有序元素
- 尽管无序列表中仍然有元素
- 将无序列表中的第一个元素设置为最低变量
- 对于无序列表中的每个元素
- 如果元素低于最低元素
- 将该元素的值分配为最低
到目前为止,我遇到的最大问题是我的柜台无法可靠地为我提供一种方法,让我可以从列表中无序地挑选出最低的数字.然后我在索引列表时遇到问题,即索引超出范围.谁能给我一些有关我要出问题的地方的反馈?
The biggest issue I'm having so far is that my counter doesn't reliably give me a way to pick out the lowest number from my list unordered. And then I'm having issues with indexing my list i.e. the index being out of range. Can anyone give me a bit of feedback on where I'm going wrong?
另外,我得到的信息我不太确定:
Also, I was given this info which I'm not really sure about:
您可以使用一种已建立的方法对称为选择排序"的列表进行排序.
You can use an established method to sort the list called the Selection Sort.
这次我不应该使用Python的内置排序方法.所有这些都应该手动完成.感谢您的帮助!
I'm not supposed to be using Python's built in sort methods this time around. It's all supposed to be done manually. Thanks for any help!
推荐答案您只是错了一些顺序:您每次都需要在订单列表中添加
You've just got some of the order wrong: you need to append to your ordered list each time around
import random unordered = list(range(10)) ordered = [] i = 0 random.shuffle(unordered) print unordered lowest = unordered[0] while len(unordered) > 0: if unordered[i] < lowest: lowest = unordered[i] i += 1 if i == len(unordered): ordered.append(lowest) unordered.remove(lowest) if unordered: lowest = unordered[0] i = 0 print(ordered)