2013-10-01 66 views
0

我是新来的python 即时寻找一个代码来泡沫排序的单词列表。Python泡泡排序字

mylist = [12, 5, 13, 8, 9, 65] 

def bubble(badList): 
    length = len(badList) - 1 
    unsorted = True 

    while unsorted: 
     for element in range(0,length): 
      unsorted = False 
      if badList[element] > badList[element + 1]: 
       hold = badList[element + 1] 
       badList[element + 1] = badList[element] 
       badList[element] = hold 
       print badList 
      else: 
       unsorted = True 

print bubble(mylist) 

这段代码是用数字来做的,我想用单词做它。 谢谢

+3

你有没有用绳子尝试过吗?它会工作。 –

+0

您好,感谢您的回复:D – user2833024

+0

请您解释我将如何做到这一点?谢谢 – user2833024

回答

1

关于Python的很多很酷的事情之一是平等和比较运算符像字符串一样工作。例如,如何比较这两个数字是相同的?

7 == 7 # true! 

两串怎么样?

"Hello world".equals("Hello world") // Java... 

"Hello world" == "Hello world" # Python! 

现在是比较器。 Python使用字典顺序来比较字符串。基本上,它会查看每个字符串中的第一个字符,并说“哪个更大?”。如果它们是相同的,它会继续向下。所以举几个例子:

"ABC" > "BAC" # false, because the character B is greater than A 
"AAAB" < "AAAC" # true, because the character B is less than C 

所以,你的代码将工作不管mylist由整数或字符串。

0

您的气泡排序代码中存在一个错误,这意味着它不会正确排序一些(也许是大多数)列表。这与列表中的值的数据类型没有任何关系(它将与数字列表或字符串列表有相同的问题)。

这里的固定代码:

def bubble(badList): 
    length = len(badList) - 1 
    unsorted = True 

    while unsorted: 
     unsorted = False    # this was moved out of the for loop 
     for element in range(0,length): 
      if badList[element] > badList[element + 1]: 
       hold = badList[element + 1] 
       badList[element + 1] = badList[element] 
       badList[element] = hold 
       print badList  # comment this out when you're done testing 
       unsorted = True  # this was moved up from the else block 

它同时适用于数字和字符串,如下所示:

lst = [12, 5, 13, 8, 9, 65] 
>>> bubble(lst) 
[5, 12, 13, 8, 9, 65] 
[5, 12, 8, 13, 9, 65] 
[5, 12, 8, 9, 13, 65] 
[5, 8, 12, 9, 13, 65] 
[5, 8, 9, 12, 13, 65] 
>>> lst 
[5, 8, 9, 12, 13, 65] 
>>> lst = ['a', 'list', 'of', 'words', 'foo', 'bar', 'baz'] 
>>> bubble(lst) 
['a', 'list', 'of', 'foo', 'words', 'bar', 'baz'] 
['a', 'list', 'of', 'foo', 'bar', 'words', 'baz'] 
['a', 'list', 'of', 'foo', 'bar', 'baz', 'words'] 
['a', 'list', 'foo', 'of', 'bar', 'baz', 'words'] 
['a', 'list', 'foo', 'bar', 'of', 'baz', 'words'] 
['a', 'list', 'foo', 'bar', 'baz', 'of', 'words'] 
['a', 'foo', 'list', 'bar', 'baz', 'of', 'words'] 
['a', 'foo', 'bar', 'list', 'baz', 'of', 'words'] 
['a', 'foo', 'bar', 'baz', 'list', 'of', 'words'] 
['a', 'bar', 'foo', 'baz', 'list', 'of', 'words'] 
['a', 'bar', 'baz', 'foo', 'list', 'of', 'words'] 
>>> lst 
['a', 'bar', 'baz', 'foo', 'list', 'of', 'words']