5 回答
TA贡献1864条经验 获得超2个赞
一种选择是这样的:
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 random
random.shuffle(groups)
for function1, function2 in zip(*groups):
function1()
function2()
输出
B1
A1
B2
A2
B3
A3
另外 - 如果有超过 2 个组,最好这样做:
for functions in zip(*groups):
for my_function in functions:
my_function()
这样,就可以轻松地将其扩展为大量组,而无需更改该部分代码。
TA贡献1820条经验 获得超10个赞
像这样的东西:
from random import shuffle
functions = ([functionA1, functionB1], [functionA2, functionB2])
for i in range(x):
for group in functions:
shuffle(group)
for func in group:
func()
TA贡献1865条经验 获得超7个赞
如果您有很多功能,最好以某种方式组织它们。例如在单独的模块中:
# file group_a.py
def function1():
print("A1")
# file group_b.by
def function1():
print("B1")
# file main.py
import group_a
import group_b
import random
first, 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的答案。
TA贡献1884条经验 获得超4个赞
以下可以扩展到任意数量的组和功能。将为三组进行说明。
from random import randrange
def rotate(arr, r):
' Roates an array '
return arr[r:] + arr[:r]
# Generate groups of functions
n = 4 # number of functions in a group
groupA = [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:
B1
C1
A1
B2
C2
A2
B3
C3
A3
B4
C4
A4
前任。2
A1
B1
C1
A2
B2
C2
A3
B3
C3
A4
B4
C4
TA贡献1848条经验 获得超6个赞
为了保持关卡的顺序,您可以分别对它们进行洗牌。
您可以将函数视为一等公民。
import random
lst = [["a1", "b1"], ["a2", 'b2']]
for el in lst:
random.shuffle(el)
print(ch)
示例输出:
[['a1', 'b1'], ['b2', 'a2']]
添加回答
举报