用字符串Python替换列表中的整数

2024-09-27 21:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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

Tags: andintegers列表bymainwithnot整数
3条回答

为什么要经历这么多的附加和弹出的麻烦,那是没有必要的

def BooHoo(n):

    for index, item in enumerate(list(range(1, (n+1))):
        if not item % 5 and not item % 3:
            lista[index] = "BooHoo"
        elif not item % 3:
            lista[index] = "Boo"
        elif not item % 5:
            lista[index] = "Hoo"
        else:
            pass

    return lista 

print(BooHoo(25))

输出

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 boohoo.py
[1, 2, 'Boo', 4, 'Hoo', 'Boo', 7, 8, 'Boo', 'Hoo', 11, 'Boo', 13, 14, 'BooHoo', 16, 17, 'Boo', 19, 'Hoo', 'Boo', 22, 23, 'Boo', 'Hoo']

在索引和列表的实际元素方面存在一些逻辑错误。我用注释#突出显示了修改/添加的行。主要是,您需要将idx替换为j,因为idx是一个索引,而{}是一个实际的元素。如果以range(n)开头,则无所谓,因为索引与j相同。但既然您在问题中提到,您想要存储从1到{}的数字,那么您需要使用range(1, n+1)

def BooHoo(n):
    main_list = []
    for x in range(1,n+1): # replaced range(n) to start from 1
        main_list.append(x)

    for idx, j in enumerate(main_list):
        if not (j % 3) and not (j % 5): # replaced idx by j
            main_list.pop(idx)
            main_list.insert(idx, 'BooHoo')
        elif not (j % 3): # replaced idx by j
                main_list.pop(idx)
                main_list.insert(idx, 'Boo')
        elif not (j % 5): # replaced idx by j
                main_list.pop(idx)
                main_list.insert(idx, 'Hoo')
        else:
            continue

    return main_list # Removed unnecessary second list

# Call the function
print (BooHoo(15))

输出

^{pr2}$

解决问题的更好方法是从一开始就构建正确的列表(通过循环或列表理解),而不是修改一个连续的数字列表。在

def BooHoo(n):
    return ['BooHoo' if not (i % 5 or i % 3) else 
               'Hoo' if not i % 5 else 
               'Boo' if not i % 3 else 
                   i for i in range(1,n+1)]

而且,更多的是为了好玩而不是有用,基于字典的解决方案:

^{pr2}$

相关问题 更多 >

    热门问题