Python实现《One man went to mow》童谣输出格式问题求助
Python实现《One man went to mow》童谣输出的格式修正方案
问题说明
需要用Python实现童谣《One man went to mow》的输出,但现有代码无法生成符合要求的格式,尤其无法正确拼接出类似“Four men, three men, two men, one man”的倒序列表内容。
现有代码
num = ['One man','Two men','Three men','Four men','Five men', 'Six men','Seven men','Eight men','Nine men','Ten men'] for i in range(0,len(num)): print(num[i],'went to mow, went to mow a meadow,') # Check if i is greater than 0, to avoid index out of range errors if i > 0: # Loop through the previous elements in the num list for n in range(i-1,-1,-1): print(num[i],num[n],'and his dog, went to mow a meadow.')
期望输出示例
One man went to mow, went to mow a meadow
One man and his dog
Went to mow a meadowTwo men went to mow
Went to mow a meadow
Two men, one man and his dog
Went to mow a meadowThree men went to mow
Went to mow a meadow
Three men, two men, one man
And his dog
Went to mow a meadowFour men went to mow
Went to mow a meadow
Four men, three men, two men, one man
And his dog
Went to mow a meadow...(以此类推至第十段)
解决方案
核心问题是现有代码未正确拼接倒序人员列表,且重复输出当前项。以下是修正后的代码,针对不同段落的格式差异做了针对性处理:
num = ['One man', 'Two men', 'Three men', 'Four men', 'Five men', 'Six men', 'Seven men', 'Eight men', 'Nine men', 'Ten men'] for i in range(len(num)): current = num[i] # 处理每段开头的换行逻辑 if i == 0: print(f"{current} went to mow, went to mow a meadow") else: print(f"{current} went to mow") print("Went to mow a meadow") # 处理人员列表和"his dog"部分的格式 if i == 0: print(f"{current} and his dog") else: # 生成从当前项到第一项的倒序列表,并拼接成字符串 people_list = num[i::-1] people_str = ", ".join(people_list) if i == 1: print(f"{people_str} and his dog") else: print(people_str) print("And his dog") # 每段结尾固定行 print("Went to mow a meadow") # 段落间添加空行(最后一段除外) if i != len(num) - 1: print()
代码关键说明
num[i::-1]:生成从当前索引i到索引0的倒序列表,比如i=3时,得到['Four men', 'Three men', 'Two men', 'One man']", ".join(people_list):将列表元素用逗号连接成符合要求的连续字符串- 分三段逻辑处理不同段落的格式差异,完全匹配期望输出的换行和拼接规则
- 通过判断是否为最后一段,控制段落间的空行分隔
内容的提问来源于stack exchange,提问作者Tommy
相关产品推荐
相关产品推荐

