-
慕斯王
一种选择是这样的:def functionA1(): print('A1')def functionA2(): print('A2')def functionA3(): print('A3')def functionB1(): print('B1')def functionB2(): print('B2')def functionB3(): print('B3')groupA = (functionA1, functionA2, functionA3)groupB = (functionB1, functionB2, functionB3)groups = [groupA, groupB]import randomrandom.shuffle(groups)for function1, function2 in zip(*groups): function1() function2()输出B1A1B2A2B3A3另外 - 如果有超过 2 个组,最好这样做:for functions in zip(*groups): for my_function in functions: my_function()这样,就可以轻松地将其扩展为大量组,而无需更改该部分代码。
-
拉莫斯之舞
像这样的东西:from random import shufflefunctions = ([functionA1, functionB1], [functionA2, functionB2])for i in range(x): for group in functions: shuffle(group) for func in group: func()
-
鸿蒙传说
如果您有很多功能,最好以某种方式组织它们。例如在单独的模块中:# file group_a.pydef function1(): print("A1")# file group_b.bydef function1(): print("B1")# file main.pyimport group_aimport group_bimport randomfirst, second = random.sample((group_a, group_b), k=2)for i in range(1, x): getattr(first, f"function{i}")() getattr(second, f"function{i}")()如果您的函数命名方案是这样的,您可以使用getattr来查找正确的函数。如果它们具有任意名称,您将需要在每个模块中创建一个列表,其中的函数按正确的顺序排列。这将类似于buran的答案。
-
慕村9548890
以下可以扩展到任意数量的组和功能。将为三组进行说明。from random import randrangedef rotate(arr, r): ' Roates an array ' return arr[r:] + arr[:r]# Generate groups of functionsn = 4 # number of functions in a groupgroupA = [lambda i = i: f'A{i}' for i in range(1, n+1)]groupB = [lambda i = i: f'B{i}' for i in range(1, n+1)]groupC = [lambda i = i: f'C{i}' for i in range(1, n+1)]# Random starting index (i.e. 0 to n-1)index = randrange(0, n)# Create function selections (rotate based upon index)selection = [rotate(x, index) for x in zip(groupA, groupB, groupC)]for funcs in selection: for f in funcs: print(f())输出例1:B1C1A1B2C2A2B3C3A3B4C4A4前任。2A1B1C1A2B2C2A3B3C3A4B4C4
-
慕勒3428872
为了保持关卡的顺序,您可以分别对它们进行洗牌。您可以将函数视为一等公民。import randomlst = [["a1", "b1"], ["a2", 'b2']]for el in lst: random.shuffle(el)print(ch)示例输出:[['a1', 'b1'], ['b2', 'a2']]