python - 我想在我的代码中实现一个功能,该功能将从列表中随机选择键和值,以便稍后将它们分配给字典
问题描述
而不是已经预先制作的名称字典作为键和特征作为值
colonists = {
'john': 'sickly',
'sarah': 'night owl',
'bill': 'nudist',
'eric': 'none'
}
我想从两个具有名称和特征的不同列表中随机选择名称和特征,并将它们分配给一个空字典。我已经尝试过各种方式自己做,但一切都不顺利。我总体上寻找建议和技巧来改进和优化我的代码。这是带有预制字典的代码:
import random
colonists = {
'john': 'sickly',
'sarah': 'night owl',
'bill': 'nudist',
'eric': 'none'
}
events = ['plague', 'day', 'clothes', 'none']
current_event = random.choice(events)
print(f"Current event is {current_event}")
for name, trait in colonists.items():
if current_event == 'clothes' and trait == 'nudist':
print(f"{name.capitalize()} is suffering due to having a {trait} trait")
elif current_event == 'day' and trait == 'night owl':
print(f"{name.capitalize()} is suffering due to having a {trait} trait")
elif current_event == 'plague' and trait == 'sickly':
print(f"{name.capitalize()} is suffering due to having a {trait} trait")
else:
print(f"{name.capitalize()} is not suffering due to having a {trait} trait")
解决方案
只需打乱列表并制作字典:
import random
names = ['john', 'sarah', 'bill', 'eric']
traits = ['sickly', 'night owl', 'nudist', 'none']
# random shuffle
# as @quamrana mentioned, you only need to shuffle one of them
random.shuffle(names)
random.shuffle(traits)
colonists = dict(zip(names, traits))
推荐阅读
- javascript - 添加分数网格游戏 JavaScript
- java - IntelliJ IDEA Ultimate 2018.3.5 重复代码未突出显示
- ios - 从后台返回后,Alamofire 进度回调停止工作
- cmake - CMake:不使用 /usr/lib64/libXmu.so
- java - Read file in java linux?
- php - How to update a php variable in the included page without reloading page
- apache-spark - Error when run structured streaming program
- java - Spring mvc 对其他包隐藏一个包
- python-3.x - 在 Gearman 中安排作业
- node.js - 如何更改 npm ll 的输出格式?