python输出从输入列表中的随机列表
我需要从列表1创建3个列表。一个具有70%的值,两个为20%和10%。
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# listOutput70 = select 70% of list1 items(randomly)
# with the remaining create two lists of 20% and 10%
#the output can be something like:
#listOutput70 = [2,7,9,8,4,10,3]
#listOutput20 = [1,5]
#listOutput10 = [6]
我已经有一些代码来生成一个百分比的输出,但仅适用于一个列表。
import random
def selector():
RandomSelection = []
mySel = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
PercentEnter= 70
New_sel_nb = len(mySel)*int(PercentEnter)/100
while len(RandomSelection) < New_sel_nb:
randomNumber = random.randrange(0, len(mySel),1)
RandomSelection.append(mySel[randomNumber])
RandomSelection = list(set(RandomSelection))
print(RandomSelection)
selector()
#[2, 3, 6, 7, 8, 9, 10]
I need to create 3 lists from my list1. One with 70% of the values and two with 20% and 10%.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# listOutput70 = select 70% of list1 items(randomly)
# with the remaining create two lists of 20% and 10%
#the output can be something like:
#listOutput70 = [2,7,9,8,4,10,3]
#listOutput20 = [1,5]
#listOutput10 = [6]
I already have some code to generate a percentage output, but works only for one list.
import random
def selector():
RandomSelection = []
mySel = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
PercentEnter= 70
New_sel_nb = len(mySel)*int(PercentEnter)/100
while len(RandomSelection) < New_sel_nb:
randomNumber = random.randrange(0, len(mySel),1)
RandomSelection.append(mySel[randomNumber])
RandomSelection = list(set(RandomSelection))
print(RandomSelection)
selector()
#[2, 3, 6, 7, 8, 9, 10]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用
random.shuffle()
将列表改组。然后使用切片来获取每个百分比。Shuffle the list with
random.shuffle()
. Then use slices to get each percentage.使用 numpy.split.split 函数 function usage:
usage:用法:
Using numpy.split function:
Usage: