产生10000位随机序列 [英] Generating a 10000 bit random sequence

查看:89
本文介绍了产生10000位随机序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比在循环中附加0和1s更有效的方法来在Python中生成10 kBit(10,000位)随机二进制序列?

Is there a more efficient way to generate a 10 kBit (10,000 bits) random binary sequence in Python than appending 0s and 1s in a loop?

推荐答案

如果您想要一个随机的二进制序列,则可能最快的方法是生成一个适当范围内的随机整数:

If you want a random binary sequence then it's probably quickest just to generate a random integer in the appropriate range:

import random
s = random.randint(0, 2**10000 - 1)

之后,这实际上取决于您要对二进制序列执行的操作.您可以使用按位运算查询单个位:

After this it really depends on what you want to do with your binary sequence. You can query individual bits using bitwise operations:

s & (1 << x)  # is bit x set?

,或者您可以使用 bitarray

or you could use a library like bitarray or bitstring if you want to make checking, setting slicing etc. easier:

from bitstring import BitArray
b = BitArray(uint=s, length=10000)
p, = b.find('0b000000')
if b[99]:
    b[100] = False
...

这篇关于产生10000位随机序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆