我正在用Python编写代码,我很难理解为什么我的代码不能工作。在
用Python编写一个名为“BooHoo”的函数,它接受一个整数n,并将从1到n的所有整数存储在一个列表中。但是,如果列表中的一个整数可以被3整除,那么列表应该包含“Boo”。如果整数可以被5整除,则列表应该包含“Hoo”。如果整数可以被3和5整除,那么列表应该包含“BooHoo”。在
def BooHoo(n):
'''
A function which returns a list of integers, and replaces integers divisible by 3 with "Boo" and integers
divisible by 5 with "Hoo" and integers divisible by 3 and 5 with "BooHoo"
Parameters
-------
n: an integer
Returns
--------
final_list: a Python list
'''
main_list = []
for x in range(n):
main_list.append(x)
for idx, j in enumerate(main_list):
if not (idx % 3) and not (idx % 5):
main_list.pop(idx)
main_list.insert(idx, 'BooHoo')
elif not (idx % 3):
main_list.pop(idx)
main_list.insert(idx, 'Boo')
elif not (idx % 5):
main_list.pop(idx)
main_list.insert(idx, 'Hoo')
else:
continue
final_list = [main_list]
return final_list
为什么要经历这么多的附加和弹出的麻烦,那是没有必要的
输出
在索引和列表的实际元素方面存在一些逻辑错误。我用注释}是一个实际的元素。如果以}的数字,那么您需要使用
#
突出显示了修改/添加的行。主要是,您需要将idx
替换为j
,因为idx
是一个索引,而{range(n)
开头,则无所谓,因为索引与j
相同。但既然您在问题中提到,您想要存储从1
到{range(1, n+1)
输出
^{pr2}$解决问题的更好方法是从一开始就构建正确的列表(通过循环或列表理解),而不是修改一个连续的数字列表。在
而且,更多的是为了好玩而不是有用,基于字典的解决方案:
^{pr2}$相关问题 更多 >
编程相关推荐