Python 3.9 DeprecationWarning: random.seed() with List as Seed
This article addresses a common error encountered in Python 3.9 when using random.seed() with a list as the seed value. The error message, 'DeprecationWarning: Seeding based on hashing is deprecated since Python 3.9 and will be removed in a subsequent version. The only supported seed types are: None, int, float, str, bytes, and bytearray.' occurs because random.seed() only accepts specific data types as seeds.
Here's the original code causing the error:
import random
lst_who = ['horse', 'lamb', 'deer']
lst_what = ['watch a movie', 'listen to a story', 'have dinner']
lst_where = ['on the grass', 'in the cinema', 'at home']
seed_input = input()
seeds = [int(seed.strip()) for seed in seed_input.strip('[]').split(',')]
random.seed(seeds)
index_who = random.randint(0, 2)
index_what = random.randint(0, 2)
index_where = random.randint(0, 2)
sentence = lst_who[index_who] + ' ' + lst_what[index_what] + ' ' + lst_where[index_where]
print(sentence)
The issue lies in the line random.seed(seeds). random.seed() expects an immutable object as the seed value. Lists are mutable, meaning they can be changed after creation. This poses a problem for the random number generator, which relies on a consistent seed to generate predictable sequences.
To fix this, you can convert the seeds list to a tuple before passing it to random.seed(). Tuples are immutable, so they are suitable for use as seeds:python
import random
lst_who = ['horse', 'lamb', 'deer'] lst_what = ['watch a movie', 'listen to a story', 'have dinner'] lst_where = ['on the grass', 'in the cinema', 'at home']
seed_input = input() seeds = [int(seed.strip()) for seed in seed_input.strip('[]').split(',')]
random.seed(tuple(seeds))
index_who = random.randint(0, 2) index_what = random.randint(0, 2) index_where = random.randint(0, 2)
sentence = lst_who[index_who] + ' ' + lst_what[index_what] + ' ' + lst_where[index_where]
print(sentence)
By making this simple change, you ensure that the seed value remains consistent, allowing the random number generator to function correctly. This prevents the DeprecationWarning and ensures your code is compatible with future versions of Python.
原文地址: http://www.cveoy.top/t/topic/cJNc 著作权归作者所有。请勿转载和采集!