【发布时间】:2016-05-31 04:11:41
【问题描述】:
我想知道是否有更简洁的方法来重新分配列表中的随机项:首先将原始项设置为变量,然后用另一个预设变量替换列表中的该项。
listofwords 是一个包含 9 个项目的列表。
random_val = random.randint(0,8)
removed_word = listofwords[randomval]
listofwords[randomval] = substitute_word
【问题讨论】:
-
请注意,您实际上并没有删除列表项。
-
迂腐,但您正在重新分配与删除。如果您想删除并重新插入(顺便说一句很慢),您将使用
.pop(randomval)然后.insert(randomval, substitute_word)但请不要这样做。只是改变你所说的你在做什么。 ;-) -
感谢 dawg - 已编辑
标签: python list python-2.7 replace