无语,求解 问问,
主要问题,就是我想从一个列表中随机的抽取一个元素,假如一个列表有5个元素那么我随机抽取一个元素,抽取5次结束,并且要保证每次取出来的元素不能重复有什么具体的方法吗。或者就是如何随机的从列表中取出一个元素,并把这个元素添加到一个新的列表中,并且把这个元素从此列表中删去。
两个问题解决哪一个都行,我上遍各种网站,真的搜不到我想要的答案呀!!
求大神带飞。 本帖最后由 jackz007 于 2021-10-27 21:32 编辑
import random
d =
e , k = d[:] , len(d)
while len(e):
x = e
e . remove(x)
print(x)
运行实况:
D:\00.Excise\Python>python x.py
3
2
5
4
1
D:\00.Excise\Python>python x.py
3
5
1
2
4
D:\00.Excise\Python> 本帖最后由 myqf123 于 2021-10-27 22:20 编辑
import random as r
list1 = ['鱼C小师妹','小甲鱼','稚辉君','不二如是','老王来也']
list2 = []
for i in range(5):
name = list1.pop(r.randint(0,len(list1)-1)) #len(list1-1) 不减 1 的话,len(list1)有可能是5,pop(5)会
list2.append(name) #超出索引范围
print(name)
print(list2)
print('-'*60)
结果: 多运行几次,试试就知道了,每次都不一样哦!
小甲鱼
老王来也
不二如是
鱼C小师妹
稚辉君
['小甲鱼', '老王来也', '不二如是', '鱼C小师妹', '稚辉君']
------------------------------------------------------------ Pythonimport random
arr = ['a', 'b', 'c', 'd', 'e']
res = []
while True:
if len(res) == len(arr):
break
x = random.choice(arr)
if x in res:
continue
res.append(x)
print(*res)c d e b a
页:
[1]