[英]How to alphabetically sort a text file in python without sort function?
I have to alphabetically sort a text file where each new word is on a new line. 我必须按字母顺序对文本文件进行排序,其中每个新单词都在新行上。 I currently have the whitespace stripped and my program prints the first letter attaching it to a integer with the ord function.
我目前去除了空格,并且我的程序打印了第一个字母,并使用ord函数将其附加到整数。 I cannot use sort and I know I have to put it into a list just not sure how.
我无法使用排序,我知道我必须将其放入列表中,只是不确定如何操作。 This is what i wrote for the lists.
这就是我为清单写的。
lists = [ [] for _ in range( 26 ) ]
If you can't use the sort()
method, the sorted()
function is your next bet. 如果您不能使用
sort()
方法,那么sorted()
函数就是您的下一个选择。
words = [...]
sorted_words = sorted(words)
Unlike words.sort()
, using sorted()
won't modify its input, and it works on arbitrary iterables. 与
words.sort()
不同,使用sorted()
不会修改其输入,并且可以在任意可迭代对象上使用。
You could use the following function to sort your list of words: 您可以使用以下功能对单词列表进行排序:
def qsort(array):
if len(array) < 2:
return array
head, *tail = array
less = qsort([item for item in tail if item < head])
more = qsort([item for item in tail if item >= head])
return less + [head] + more
For the range command you have to put two exclusive integers as parameters for example range(0,11) will pick a number between 1 and 10. This is probably why you can use range(). 对于range命令,您必须放入两个互斥整数作为参数,例如range(0,11)将选择一个介于1和10之间的数字。这可能就是您可以使用range()的原因。 Also you need to use a column to follow range():.
另外,您需要使用一列来跟随range():。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.