如何按字母顺序列出列表并正确格式化?

时间:2013-12-02 21:12:27

标签: python string for-loop format alphabetical

我有一个项目问题,说“编写一个方法,用户输入的单词/字符串,并按字母顺序排序。”

我已经解决了基本方法,但问题是我需要像这样格式化它:

1#....................(input1)
2#....................(input2) 

他们输入的输入很多。
我无法弄清楚如何格式化它!我已经在for循环中使用了计数器,但我不确定从那里开始。

def wordSort(wordList):
    sortedList = sorted(wordList)
    return sortedList

wordList = []

while True:
    word = raw_input("Please enter a word").title()

    if word == "*":
        break
    wordList.append (word)


print ("The words you are listed in alphabetical order are:")


wordSort(wordList)

sum = 0

for x in wordSort(wordList):
    sum = sum + 1

print ("#%d %s") %(sum, wordSort(wordList))

3 个答案:

答案 0 :(得分:2)

要修复代码,您可以执行以下操作:

sortedWords = wordSort(wordList)
for x in sortedWords:
    print ("#%d %s") %(sum + 1, sortedWords[sum])
    sum = sum + 1

您可以使用enumerate()

使其更简单
sortedWords = wordSort(wordList)
for i, word in enumerate(sortedWords):
    print ("#%d %s") %(i, word)

答案 1 :(得分:0)

http://docs.python.org/2/library/functions.html#enumerate怎么样?

然后遍历已排序和枚举的列表

Ps:我不会将wordSort定义为委托给sort。

答案 2 :(得分:0)

def get_words():
    words = []
    while True:
        word = raw_input('Please enter a word (or Enter to quit): ').strip().title()
        if word:
            words.append(word)
        else:
            return words

def main():
    words = get_words()

    print ("The words you entered, in alphabetical order, are:")
    for i,word in enumerate(sorted(words), 1):
        print('#{:>2d} {:.>16}'.format(i, ' '+word))

if __name__=="__main__":
    main()

导致

Please enter a word (or Enter to quit): giraffe
Please enter a word (or Enter to quit): tiger
Please enter a word (or Enter to quit): llama
Please enter a word (or Enter to quit): gnu
Please enter a word (or Enter to quit): albatross
Please enter a word (or Enter to quit): 
The words you entered, in alphabetical order, are:
# 1 ...... Albatross
# 2 ........ Giraffe
# 3 ............ Gnu
# 4 .......... Llama
# 5 .......... Tiger