- 您可以
while
通过仅使用for
循环和range()
对象来简化循环。
- 使用函数。他们是你的朋友。
- 将列表的内容连接在一起使用
', '.join(your_list)
这是我解决问题的方法:
def lyrics(men):
verses = []
verses.append(str(len(men)) + ' men went to mow,')
verses.append('Went to mow a meadow,')
verses.append(', '.join(reversed(men)) + ' and his dog,')
return '\n'.join(verses)
num_men = int(raw_input('How many men will mow the meadow? '))
song = []
men = []
for man in range(1, num_men + 1):
men.append(str(man) + ' men')
song.append(lyrics(men))
print '\n\n'.join(song)
print
print 'your meadow has been mowed'
要真正让您的代码吐出真正的歌曲(带有拼写的数字),请使用字典将数字映射到单词:
num_men = int(raw_input('How many men will mow the meadow? '))
def lyrics(men):
return '{num_men} went to mow,\nWent to mow a meadow,\n{men} and his dog'.format(
num_men=len(men),
men=', '.join(reversed(men)).capitalize()
)
song = []
men = []
numbers = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine'
}
for man in range(1, num_men + 1):
men.append('{} {}'.format(numbers[man], 'man' if man == 1 else 'men'))
song.append(lyrics(men))
print '\n\n'.join(song)
print
print 'your meadow has been mowed'