将函数添加到列表中但仍能执行它们

0 投票
1 回答
55 浏览
提问于 2025-04-14 17:17

我对Python和编程还比较陌生。现在我在做一个构建器,有四种可以选择的构建模块。模块a是必须的,其他三个模块b、c、d是可选的。我希望用户能够选择“我想使用模块b、c、d”或者这些模块的任意组合。此外,选择使用哪个模块是随机的。

现在我用7个if、elif和else的循环来写这个,但我希望能有更简洁的方法来实现。

import random

blocks_to_use = 10
useb = True
usec = False
used = True

def a():
    # build block a
    return # block_a

def b():
    # build block b
    return # block_b

def c():
    # build block c
    return # block_c

def d():
    # build block d
    return # block_d

def build():
    tower = ''
    if useb and not usec and not used:
        for block in range(blocks_to_use):
            tower = tower + random.choice((a(), b()))
    elif not useb and usec and not used:
        for block in range(blocks_to_use):
            tower = tower + random.choice((a(), c()))
    elif not useb and not usec and used:
        for block in range(blocks_to_use):
            tower = tower + random.choice((a(), d()))
    elif useb and usec and not used:
        for block in range(blocks_to_use):
            tower = tower + random.choice((a(), b(), c()))
    elif useb and not usec and used:
        for block in range(blocks_to_use):
            tower = tower + random.choice((a(), b(), d()))
    elif not useb and usec and used:
        for block in range(blocks_to_use):
            tower = tower + random.choice((a(), c(), d()))
    else:
        for block in range(blocks_to_use):
            tower = tower + random.choice((a(), b(), c(), d()))
    return tower

我希望能写一个像modules_to_use这样的函数,把用户指定的模块b、c、d添加到一个列表里,但我不知道该怎么做。

1 个回答

-1

根据给出的描述,我会这样做。调用 build() 函数时,可以传入任意数量的块(这些块可以是函数,里面可以定义进一步的指令来完成想要的任务)。

import math
blocks_to_use = 10

def a():
    return 'a'
def b():
    return 'b'
def c():
    return 'c'
def d():
    return 'd'


def getrandomprops(all_blocks, maxsumofblocks):
    num_of_blocks={}
    ratio = math.floor(maxsumofblocks/len(all_blocks))
    [num_of_blocks.update({i:ratio}) for i in all_blocks]
    extra = maxsumofblocks-ratio*len(all_blocks)
    [num_of_blocks.update({k:num_of_blocks[k]+1}) for idx,k in enumerate(num_of_blocks) if idx<extra]
    return num_of_blocks

def build(*args):
    _blocks = [block for block in args]
    _blocks.insert(0, a())
    block_proportions = getrandomprops(_blocks, blocks_to_use)
    [print('Block: {} ------------> Number of blocks to use: {}\n'.format(k,v)) for k,v in block_proportions.items()]

为了测试这个,定义一些块(下面我定义了 b、c 和 d,但你也可以用 1 或 2)。

b, c, d = b(), c(), d()
build(b,c,d)

结果

块:a ------------> 使用的块数量:3

块:b ------------> 使用的块数量:3

块:c ------------> 使用的块数量:2

块:d ------------> 使用的块数量:2

撰写回答