蝴蝶不菲
:=您可以使用Python 3.8 中的赋值表达式运算符通过列表推导来做到这一点。>>> import random>>> dic={'1':[(1,2,4,3),(1,2,3,1)],'2':[(2,4,2,3),(2,6,5,3)],'3':[(3,5,9,1),(3,2,5,2),(3,7,8,1)]}>>> y = (1,2,4,3)>>> n = 20>>> [(y:=random.choice(dic[str(y[-1])])) for _ in range(n)][(3, 2, 5, 2), (2, 4, 2, 3), (3, 7, 8, 1), (1, 2, 4, 3), (3, 2, 5, 2), (2, 4, 2, 3), (3, 7, 8, 1), (1, 2, 4, 3), (3, 5, 9, 1), (1, 2, 3, 1), (1, 2, 3, 1), (1, 2, 3, 1), (1, 2, 4, 3), (3, 2, 5, 2), (2, 4, 2, 3), (3, 7, 8, 1), (1, 2, 3, 1), (1, 2, 3, 1), (1, 2, 3, 1), (1, 2, 4, 3)]最初的选择y并不重要,只要str(y[-1])是dic.
qq_遁去的一_1
我认为使用递归是解决这个问题的好方法。import randomdef concatenator(dictionary, i, key=1): if i > 0: tuple_chosen = random.choice(dictionary[str(key)]) next_key = tuple_chosen[-1] return str(tuple_chosen) + concatenator(dictionary, i-1, key=next_key) else: return ""按如下方式使用此函数:(i 是您希望最后拥有的元组数)dic = {'1': [(1,2,4,3),(1,2,3,1)], '2': [(2,4,2,3),(2,6,5,3)], '3': [(3,5,9,1),(3,2,5,2),(3,7,8,1)]}concatenator(dic, 5)# outputs: '(1, 2, 3, 1)(1, 2, 3, 1)(1, 2, 3, 1)(1, 2, 3, 1)(1, 2, 3, 1)'