python列表随机选择并删除_关于列表:显示随机选择(Python)

我有一个项目列表[],我想从中随机显示一个项目,但在最后X个请求中,显示的项目不能重复一次以上。

list1=第1项,第2项,第3项,第4项,第5项,第6项,第7项,第8项,第9项,第10项

显示随机选择从上面的列表中

list2=将最后显示的项目存储在list2中,该列表只应存储7项目,而不是更多

随机显示从列表中选择但使当然不存在于表2

这是正确的方法吗?不管怎样,我想知道如何限制一个列表只存储7个项目?

谢谢

重复:stackoverflow.com/questions/1058712/…。可能是家庭作业。

collections.deque是python中唯一自然支持绑定的序列类型(并且仅在python 2.6及更高版本中),如果使用python 2.6或更高版本:

# Setup

from collections import deque

from random import choice

used = deque(maxlen=7)

# Now your sampling bit

item = random.choice([x for x in list1 if x not in used])

used.append(item)

如果使用的是python 2.5或更低版本,则不能使用maxlen参数,需要再执行一个操作来切掉deque前面的部分:

while len(used) > 7:

used.popleft()

这并不是最有效的方法,但确实有效。如果您需要速度,并且您的对象是可散列的(最不可变的类型),请考虑使用字典作为"已用"列表。

另外,如果只需要执行一次,random.shuffle方法也可以工作。

很高兴知道德克,谢谢!:)

这就是你想要的吗?

list1 = range(10)

import random

random.shuffle(list1)

list2 = list1[:7]

for item in list2:

print item

print list1[7]

换句话说,看看random.shuffle()。如果要保持原始列表的完整性,可以复制它:list_copy = list1[:]。

object=random.shuffle(list1)返回none,它不能将值存储在对象中吗?

不,random.shuffle()在适当的位置修改了列表(这就是为什么要复制的原因)。你可以从random.choice()的列表中得到一个随机项。

您可以尝试使用生成器函数,并在需要新项目时调用.next()。

import random

def randomizer(l, x):

penalty_box = []

random.shuffle(l)

while True:

element = l.pop(0)

# for show

print penalty_box, l

yield element

penalty_box.append(element)

if len(penalty_box) > x:

# penalty time over for the first element in the box

# reinsert randomly into the list

element = penalty_box.pop(0)

i = random.randint(0, len(l))

l.insert(i, element)

用法示例:

>>> r = randomizer([1,2, 3, 4, 5, 6, 7, 8], 3)

>>> r.next()

[] [1, 5, 2, 6, 4, 8, 7]

3

>>> r.next()

[3] [5, 2, 6, 4, 8, 7]

1

>>> r.next()

[3, 1] [2, 6, 4, 8, 7]

5

>>> r.next()

[3, 1, 5] [6, 4, 8, 7]

2

>>> r.next()

[1, 5, 2] [4, 3, 8, 7]

6

>>> r.next()

[5, 2, 6] [4, 3, 8, 7]

1

>>> r.next()

[2, 6, 1] [5, 3, 8, 7]

4

>>> r.next()

[6, 1, 4] [3, 8, 2, 7]

5

我将使用set objects获取列表1中而不是列表2中的项目列表:

import random

list1 = set(["item1","item2","item3","item4","item5",

"item6","item7","item8","item9","item10"])

list2 = []

while True:  # Or something

selection = random.choice(tuple(list1.difference(set(list2))))

print(selection)

list2.append(selection)

if len(list2) > 7:

list2 = list2[-7:]

比如:

# Setup

import random

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

list2 = []

# Loop for as long as you want to display items

while loopCondition:

index = random.randint(0, len(list1)-1)

item = list1.pop(index)

print item

list2.append(item)

if(len(list2) > 7):

list1.append(list2.pop(0))

无限循环只是为了演示?

当然。Nimbuz指定他有一些"请求"进入,所以我将其表示为一个无限循环。我会修改,以免有人把它放进去。:)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值