首页 > 解决方案 > 我想在我的代码中实现一个功能,该功能将从列表中随机选择键和值,以便稍后将它们分配给字典

问题描述

而不是已经预先制作的名称字典作为键和特征作为值

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")

标签: python

解决方案


只需打乱列表并制作字典:

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))

推荐阅读