如何在列表中放入括号?

时间:2019-04-26 18:48:54

标签: list

因此,对于此分配,我们需要将随机掷骰子添加到列表中,然后需要在重复数字周围添加括号。 (例如:(1,1,1),2,3,(4,4))

from random import randint

diceTosses = []

for i in range(0, 20) :
    diceTosses.append(randint(1,6))

value = diceTosses

inRun = False

for i in range(1, len(diceTosses)):
    if inRun and diceTosses[i] != value[i - 1]:
        print(")", end="")
        inRun = False

inRun = True

for i in range(1, len(diceTosses)):
    if inRun and diceTosses[i] != [i + 1]:
        print("(", end="")
        inRun = True

print(diceTosses)

我成功地将卷放入列表中,但是我的代码似乎只打印了最左边的括号,而不在列表中,我不确定自己做错了什么。

1 个答案:

答案 0 :(得分:0)

如果要查看结果,请参见以下代码: (1,1,1,1),(2,2,2),(3,3,3,3,3,3),(5,5,5),(6,6,6,6)< / p>

diceTosses.sort()
inRun = True

for i in range(1, len(diceTosses)):
    if inRun:
        print("(", end="")
    if diceTosses[i] == diceTosses[i - 1]:
        print(diceTosses[i-1],",", end="")
        inRun = False
    else:
        print(diceTosses[i-1], end= "),")
        inRun=True
if inRun:
    print("(", end="")
print(diceTosses[i], end= ")")