Python 如何按字母顺序排列列表并正确设置格式?
我的一个项目问题是“编写一个方法,将用户输入的单词/字符串按字母顺序排序。”Python 如何按字母顺序排列列表并正确设置格式?,python,string,for-loop,format,alphabetical,Python,String,For Loop,Format,Alphabetical,我的一个项目问题是“编写一个方法,将用户输入的单词/字符串按字母顺序排序。” 我已经制定了基本方法,但问题是我需要将其格式化如下: 1#....................(input1) 2#....................(input2) 无论他们输入多少输入。 我不太明白如何格式化它!我已经有了一个for循环中的计数器,但我不确定从那里去哪里 def wordSort(wordList): sortedList = sorted(wordList) retu
我已经制定了基本方法,但问题是我需要将其格式化如下:
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))
怎么样
然后迭代排序和枚举列表
Ps:我不会定义wordSort只是为了将其委托给sorted。要修复代码,可以执行以下操作:
sortedWords = wordSort(wordList)
for x in sortedWords:
print ("#%d %s") %(sum + 1, sortedWords[sum])
sum = sum + 1
您可以使用enumerate()
使其更简单:
导致
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
您对
wordSort()
的第一次调用没有任何作用sorted()
不修改原始列表。如何:'{:>2}{:.>16}。格式(i,word)
(或者甚至可能'+word
)-避免整个“领导者”thingy@Jon克莱门茨:哦,太好了!你的get_words
可能是(类似于):在iter中返回[word.title()(lambda:raw_input('word:')).strip(),'')
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