![](/img/trans.png)
[英]openpyxl python3 — formatting whole rows ellicits strange behavior
[英]strange random seed behavior in Python3
即使使用random.seed(myseed)
输出一组数字也不会给出相同的顺序。 这仅发生在Python3中,而不发生在Python2中(都在Debian稳定系统上)。 是我的代码有错误还是有问题?
import random
seed=20.0
random.seed(seed)
print("seed: {}".format(seed))
test = [str(random.randint(0,1000)) for _ in range(10)]
print(', '.join(test))
ss = set(test)
print(', '.join(ss))
下面的Python3在每次运行时都给出了不同的序列,但是Python2在所有运行时都给出了相似的序列(符合预期)。
$ python3 --version
Python 3.4.2
$ python2 --version
Python 2.7.9
#same sequences
$ python2 randtest.py
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686
$ python2 randtest.py
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686
$ python2 randtest.py
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686
#diff sequences
$ python3 randtest.py
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
926, 690, 784, 702, 740, 927, 266, 154, 901, 805
$ python3 randtest.py
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
702, 926, 784, 901, 154, 266, 805, 690, 740, 927
$ python3 randtest.py
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
805, 926, 901, 784, 740, 927, 154, 690, 266, 702
您实际上是不正确的。 Python 3返回相同的数字集。 您假设每次执行python时set
无序容器的顺序都相同,这是不正确的。
例如,对于最后两个python3测试:
>>> a = set([702, 926, 784, 901, 154, 266, 805, 690, 740, 927])
>>> b = set([805, 926, 901, 784, 740, 927, 154, 690, 266, 702])
>>> a == b
True
您可以使用sorted
确保您的sets
正确sorted
print(', '.join(sorted(test)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.