gpt4 book ai didi

python - 从列表中制作字典并分成两部分

转载 作者:行者123 更新时间:2023-12-01 02:30:34 24 4
gpt4 key购买 nike

我有一份名单。我的任务是根据列表制作一本字典,然后按性别将其分为两部分。我了解如何制作一本字典,但如何将其除以二并返回它们。这是我到目前为止所做的:

def to_dictionary(names: list) -> dict:
""" Make a dictionary from a list of names."""
dct = dict()
for i in names:
dct[i] = names.count(i)
return dct


def to_sex_dicts(names_dict: dict) -> tuple:
"""Divide the names by sex to 2 different dictionaries."""


if __name__ == '__main__':
example_names = ("Kate:F\n" * 1000 + "Alex:M\n" * 800 + "Marina:F\n" * 600 + "Artyom:M\n" * 400).rstrip("\n").split("\n")
people = to_dictionary(example_names)
print(people)
male_names, female_names = to_sex_dicts(people)
print(male_names)
print(female_names)

最佳答案

你可以使用字典理解,即

def to_sex_dicts(names_dict: dict) -> tuple:
"""Divide the names by sex to 2 different dictionaries."""
m = {i : names_dict.get(i) for i in names_dict.keys() if ':M' in i}
f = {i : names_dict.get(i) for i in names_dict.keys() if ':F' in i}
return m,f

male_names, female_names = to_sex_dicts(people)
print(male_names)
{'Artyom:M': 400, 'Alex:M': 800}

print(female_names)
{'Marina:F': 600, 'Kate:F': 1000}

关于python - 从列表中制作字典并分成两部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46863368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com