我想生成随机长度和模式的方括号,例如,[] ][ [] ][ [] [[ ]] []。
目前,我的程序可以随机生成方括号,但是随机生成的次数不确定,因此,我的程序生成了以下结果:
[] [] [] [] [] []
[] [] []
[] [] [] [] []
这些方括号中没有任何随机性,只有显示的方括号数量是随机的。
我想知道如何使方括号的顺序随机,并且显示的方括号数量也是随机的。
下面是我的代码:
import random
import string
def randomGen(N):
return random.randint(1,N)
char1 = '['
char2 = ']'
finalist = []
newList = []
newList2 = []
newValue = randomGen(99)
for i in range(newValue):
newList = char1
newList2 = char2
finalist.append(newList + newList2)
for everChar in finalist:
print everChar,
感谢您的选择。
random.choice('[]')
可以很好地完成任务,并且在我看来更易读。 - lanzz"".join(random.choice('[]') for _ in range(random.randint(1, 99)))
:) - thefourtheyejoin()
在列表上的速度更快,而不是生成器表达式。 - Grijesh Chauhan