标题不太好,抱歉。
我是python的新手,我正在玩字典来加深我对它们的理解。
为了练习,我正在组建一支由11名球员组成的足球队。每个玩家都是一本存储在列表中的字典。
所以每个玩家都有自己的字典,但所有的键都是一样的,只是值会改变。
我已经确定了球员的位置,现在我想增加球员的年龄。这就是我所拥有的:
footballers = []
for populating in range(11): #populating = to get footballers
new_player = {"position": 'goalkeeper',}
footballers.append(new_player)
for baller in footballers[1:5]:
baller["position"] = 'defender'
print (baller)
for player in footballers[5:8]:
player["position"] = "midfield"
for player in footballers[8:11]:
player["position"] = "forward"
import random
for baller in footballers:
baller["age"] = random.randint (17, 34)
print (baller)
这很有效,我得到了想要的结果。但是,每次运行代码时,年龄都会发生变化。
我该如何使它运行一次,并且密钥的值保持不变?
我知道我可以自己输入年龄,但如果我想在整个联盟中占据一席之地,我不会这么做。
我尝试过其他方法,比如在另一个字典列表中创建age:value,但我不知道如何将两者组合在一起。
我这里缺什么了吗?
感谢
种子允许在每次调用时用相同的值"随机"填充列表
将种子置于循环之外很重要。
import random # good practice is to have imports at the top
footballers = []
for populating in range(11):
new_player = {"position": 'goalkeeper',}
footballers.append(new_player)
for baller in footballers[1:5]:
baller["position"] = 'defender'
print (baller)
for player in footballers[5:8]:
player["position"] = "midfield"
for player in footballers[8:11]:
player["position"] = "forward"
random.seed(42)
# the correct position is anywhere before the loop to have the same ages every call
for baller in footballers:
## random.seed(42) # Wrong position - will result in each player have the same age
baller["age"] = random.randint (17, 34)
print (baller)
注:
- 当您在jupyter中运行代码时,
random.seed()
需要与随机调用位于同一单元格中 - 42只是一个例子,你可以使用任何正整数