从一个元组 - python中取一个字符串

时间:2016-03-23 03:38:40

标签: python

我有一个元组和一个随机字符串:

AllSands = "GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"
found_sand = random.choice(AllSands)

但之后,我想从元组中取出随机字符串,因此随机部分可以再次运行,而不是相同的颜色。

5 个答案:

答案 0 :(得分:5)

您不能改变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)的{​​{1}}搜索和复制工作:

remove

答案 1 :(得分:2)

元组是不可变的,因此无法将其删除。您可以使用较少的元素创建一个新的元素。

>>> AllSands = "GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"
>>> AllSands = AllSands[1:]
>>> AllSands
('RED', 'PINK', 'BLACK', 'WHITE', 'ORANGE', 'PURPLE', 'BROWN', 'GREY')

但你可能只想迭代改组后的元组:

AllSands = "GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"
>>> all_ = list(AllSands)
>>> random.shuffle(all_)
>>> all_
['WHITE', 'BLACK', 'PURPLE', 'RED', 'PINK', 'ORANGE', 'GREY', 'GREEN', 'BROWN']
>>> random.shuffle(all_)
>>> all_
['GREEN', 'BLACK', 'PURPLE', 'GREY', 'PINK', 'BROWN', 'RED', 'WHITE', 'ORANGE']

答案 2 :(得分:2)

我只需要AllSands列表,然后shuffle

>>> AllSands = ["GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"]
>>> import random
>>> random.shuffle(AllSands)
>>> AllSands
['BROWN', 'WHITE', 'ORANGE', 'GREY', 'PINK', 'PURPLE', 'GREEN', 'BLACK', 'RED']

如果您知道您不需要整个列表,则可以使用sample intead

>>> random.sample(AllSands, 3)
['PINK', 'BROWN', 'ORANGE']

这些方法比一次选择一个随机项目然后从列表/元组中删除它更有效

你也可以有一个返回迭代器的函数,比如这个

>>> def shuffler(items):
...     items = list(items)
...     random.shuffle(items)
...     return iter(items)
... 
>>> sands = shuffler(AllSands)
>>> next(sands)
'RED'
>>> next(sands)
'PURPLE'
>>> next(sands)
'WHITE'
>>> next(sands)
'GREEN'

答案 3 :(得分:0)

一种有效的方法是用列表替换元组并执行以下操作:

AllSands = ["GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"]
index = random.randrange(len(AllSands))
found_sand = AllSands.pop(index)

答案 4 :(得分:0)

你可以使用random.shuffle()来获得你想要的东西,但是如果你真的想要从元组中“删除”一个元素(实际上元组是不可变的),试试这个:

import random 
AllSands = "GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"
found_sand = random.choice(AllSands)
AllSands = tuple( x for x in AllSands if x != found_sand)
found_sand = random.choice(AllSands)