免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 21434 | 回复: 9
打印 上一主题 下一主题

怎么在列表里随机取一个数? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-04-12 16:14 |只看该作者 |倒序浏览
例a=[1,2,5,8,9,6,3,2,1,4,55,99]

论坛徽章:
0
2 [报告]
发表于 2010-04-12 16:25 |只看该作者
>>> random.randint(0,10)
3
>>> random.randint(0,10)
6
>>> random.randint(0,10)
8
>>> random.randrange(0,10)
0
>>> random.randrange(0,10)
0
>>> random.randrange(0,10)
5
>>> random.randrange(0,10)
8
>>> random.randrange(0,10)
7
>>> random.randrange(0,10)
8
>>> random.randrange(0,10)
5
>>> random.randrange(0,10)
2
randrange和randint到底有什么区别

论坛徽章:
0
3 [报告]
发表于 2010-04-12 16:55 |只看该作者
回复 2# wqjwftcaqr


    help(randrom) 看看文档不就清楚了

论坛徽章:
0
4 [报告]
发表于 2010-04-12 17:14 |只看该作者
回复  wqjwftcaqr


    help(randrom) 看看文档不就清楚了
千年沉寂 发表于 2010-04-12 16:55



    知道的话告诉我好啦,谢谢啦

论坛徽章:
0
5 [报告]
发表于 2010-04-12 18:06 |只看该作者
|  randint(self, a, b)
     |      Return random integer in range [a, b], including both end points.
     |  
     |  randrange(self, start, stop=None, step=1, int=<type 'int'>, default=None, maxwidth=9007199254740992L)
     |      Choose a random item from range(start, stop[, step]).
     |      
     |      This fixes the problem with randint() which includes the
     |      endpoint; in Python this is usually not what you want.
     |      Do not supply the 'int', 'default', and 'maxwidth' arguments.

貌似是末尾的点是否被随机到的问题,如果是randint的话,a和b都有可能被随机到,但是randrange就不会随机到b

PS:你的问题应该可以这么写
  1. a[random.randrange(0,len(a))]
复制代码

论坛徽章:
0
6 [报告]
发表于 2010-04-12 18:07 |只看该作者
如果你用randint的话,随机到a[len(a)]就溢出了,我想应该是这样

论坛徽章:
0
7 [报告]
发表于 2010-04-13 08:58 |只看该作者
如果你用randint的话,随机到a[len(a)]就溢出了,我想应该是这样
daybreakcx 发表于 2010-04-12 18:07



    果然有一定的道理,但我想这二个函数差别只在于此,好象有点大才小用

论坛徽章:
0
8 [报告]
发表于 2010-04-13 11:30 |只看该作者
其实有个简单的办法。

>>> a = [2, 10, 30]
>>> random.choice(a)
2

如果要len的方法的话:

>>> a[random.randint(0, len(a)-1)]
30

论坛徽章:
0
9 [报告]
发表于 2010-04-13 14:11 |只看该作者
random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型,即list, tuple

论坛徽章:
0
10 [报告]
发表于 2010-04-14 11:00 |只看该作者
我自己想的方法是:
NList[i]+=str(number.pop(random.randint(0,len(number)-1)))
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP