gpt4 book ai didi

python - 你如何使用循环根据键分配字典值

转载 作者:太空狗 更新时间:2023-10-30 02:53:09 25 4
gpt4 key购买 nike

我正在尝试遍历用于创建字典键并根据几个不同类别分配值的列表

例如:

list = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']

my_dict = {}

for i in range(len(list)):
if any("cat" in s for s in list):
my_dict[list[i]] = 'categorical'
if any("num" in s for s in list):
my_dict[list[i]] = 'numerical'

我正在尝试获取一个会循环并导致以下结果的字典:

my_dict = {'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical', 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'}

感谢您的帮助!

最佳答案

如果您可以假设列表中的值将匹配您的查找之一,您可以这样做:

items = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']
matches = {'num': 'numerical', 'cat': 'categorical'}
result = {i: [v for k, v in matches.items() if k in i][0] for i in items}
print(result)

如何?

这使用字典将所需的搜索字符串映射到匹配的值。然后它使用循环理解来搜索字典中的每个值并返回匹配的值。该值用作字典理解中的值。

结果:

{'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical',
'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'
}

关于python - 你如何使用循环根据键分配字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711647/

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