我有一个元组和一个随机字符串:
AllSands = "GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"
found_sand = random.choice(AllSands)
但是之后,我想从元组中取出随机字符串,以便可以再次运行随机部分,而不必使用相同的颜色。
最佳答案
您不能变异tuple
,只能创建新的tuple
。如果使用list
,这样做会更容易:
AllSands = ["GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"]
found_sand = random.choice(AllSands)
AllSands.remove(found_sand)
当然,更简单的方法是根据需要随机播放和
pop
,这消除了O(n)
搜索和复制remove
的工作:AllSands = ["GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"]
random.shuffle(AllSands)
found_sand = AllSands.pop() # Each time you call pop, you "find" a new value
关于python - 从元组中取出字符串-python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36169390/