简体   繁体   English

如何使用for和while循环使用python按字母顺序排序?

[英]How to use for and while loop to sort in alphabetical order using python?

I'm still trying to learn on python.我仍在尝试学习python。 I've created a list of fruit as follow我创建了一个水果列表如下

fruitList = ["pear","apple","strawberry","banana","orange"]

I would like to print them out in alphabetical order using for loop and while loop.我想使用 for 循环和 while 循环按字母顺序打印它们。

   fruitList.sort()

because python have this function called sort() thus, I'm able to sort.因为python有这个叫做sort()的函数,所以我可以排序。 But what if I do not want to use the sort function?但是如果我不想使用排序功能怎么办?

However, right now, I've issue on how to sort using while loop?但是,现在,我有关于如何使用 while 循环进行排序的问题? can someone tell me how am I able to do so?有人能告诉我我怎么能这样做吗? This is what I've tried, using len()这是我尝试过的,使用 len()

for fruit in fruitList:
    while (len(fruitList[0]) > len(fruit[0])):
            fruit += 1
            print fruit
            continue

Nothing is printed when I run this program.当我运行这个程序时没有打印任何内容。 In a while loop, am I suppose to compare with the index[0] or can I use sort function as well?在 while 循环中,我是想与 index[0] 进行比较还是也可以使用 sort 函数?

you can do so:你可以这样做:

for f in sorted(fruitList):
    print(f)

and with while:并同时:

while fruitList:
    print(min(fruitList))
    fruitList.remove(min(fruitList))

But I mean, using "while" is a bad idea但我的意思是,使用“while”是个坏主意

PS sort() is not a function, It is a list method PS sort() 不是函数,它是一个列表方法

The build in sort rutines does not require usage of neither for or While内置排序程序不需要使用 for 或 While

If you want to learn for/while, look at some tutorials or something.如果你想学一会儿,看看一些教程什么的。

https://wiki.python.org/moin/ForLoop https://wiki.python.org/moin/ForLoop

To sort your list do something like this要对您的列表进行排序,请执行以下操作

fruitList = ["pear","apple","strawberry","banana","orange"]
print sorted(fruitList)
print fruitList
fruitList.sort()
print fruitList

output :输出 :

['apple', 'banana', 'orange', 'pear', 'strawberry']
['pear', 'apple', 'strawberry', 'banana', 'orange']
['apple', 'banana', 'orange', 'pear', 'strawberry']

First of all you should chose a sort algorithm, IMO one of the most simple algorithms to understand is Bubble sort (But one of the most inefficient too!)首先,您应该选择一种排序算法,IMO 最容易理解的算法之一是冒泡排序(但也是最低效的算法之一!)

swaped = True #Just to enter the first time
while swaped:
    swaped = False
    for i in range(len(fruitList)-1):
        if fruitList[i] > fruitList[i+1]:
            aux = fruitList[i]
            fruitList[i] = fruitList[i+1]
            fruitList[i+1] = aux
            swaped = True
print(fruitList)

OK, first of all you're trying to sort according to alphabetical, then why are you considering the length of the word on your list instead of their name?好的,首先您要尝试按字母顺序排序,那么您为什么要考虑列表中单词的长度而不是它们的名称?

Also, there are some mistakes in your code and I don't understand what you're trying to do.此外,您的代码中存在一些错误,我不明白您要做什么。

for fruit in fruitList:
    while (len(fruitList[0]) > len(fruit[0])):
        fruit += 1
        print fruit
        continue

First, len(fruitList[0]) is the length of the first item in your list (let's say it's pear ).首先, len(fruitList[0])是列表中第一项的长度(假设它是pear )。

In the first iteration, fruit will be fruitList[0] , pear .在第一次迭代中, fruit将是fruitList[0]pear

When you're doing len(fruitList[0]) > len(fruit[0]) you're doing (in the first iteration) len("pear") > len('p') which is always 'True' as long as you don't have an empty string ... in which case fruit[0] would throw an error.当你在做len(fruitList[0]) > len(fruit[0])你在做(在第一次迭代中) len("pear") > len('p')总是 'True' 作为只要您没有空字符串……在这种情况下, fruit[0]会抛出错误。 Now, why are you doing this?现在,你为什么要这样做? What are you trying to do?你想做什么?

Anyway, let's move on, since the above condition was 'True', then the next line of code is fruit +=1 but fruit is a string and '1' is an int, so you're trying to add a 'str' + 'int' which raises an error.不管怎样,让我们​​继续,因为上面的条件是'True',那么下一行代码是fruit +=1但是fruit是一个字符串而'1' 是一个int,所以你试图添加一个'str' + 'int' 引发错误。

Sooooo.... your code doesn't run, it throws an error, if you're saying that your code doesn't print anything, then you're getting 'False' in your while chunk, so the code you posted isn't the exact same thing you're running in your computer, am I right? Sooooo .... 你的代码没有运行,它会抛出一个错误,如果你说你的代码没有打印任何东西,那么你的 while 块中就会出现“假”,所以你发布的代码是与您在计算机中运行的完全相同,对吗?

Finnally, to answer your question, to order your list in alphabetical order, you have to check for the letters.最后,要回答您的问题,要按字母顺序排列您的列表,您必须检查字母。

First set the first item in the list as the first item.首先将列表中的第一项设置为第一项。 Then check the second item in your list and compare with the item before, if the second goes before, then move it.然后检查列表中的第二个项目并与之前的项目进行比较,如果第二个在前面,则移动它。 Then check the next item, compare with the item before it, if it goes before, then compare with the item before that one and move accordingly... repeat until you've check everyitem in the list.然后检查下一个项目,与它之前的项目进行比较,如果它在之前,则与该项目之前的项目进行比较并相应地移动......重复直到您检查了列表中的每个项目。 ---> Or use Bubble sort as explained above (just read that answer) ---> 或者使用上面解释的冒泡排序(只需阅读该答案)

Now you iterate over the list, and for each fruit you sort the list again and again.现在您遍历列表,并为每个水果一次又一次地对列表进行排序。 You don't need this.你不需要这个。 Just do做就是了

print sorted(fruitList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM