gpt4 book ai didi

python - 在 for 循环中从字典中插入和删除——最佳方法?

转载 作者:行者123 更新时间:2023-12-01 09:00:56 24 4
gpt4 key购买 nike

我有一个看起来像这样的字典:

{attribute_1 : True,
attribute_2 : False,
attribute_3 : 'foo', # Can be one of multiple text options here
attribute_4 : 5,} # Can be one of multiple numerical options here

我需要对其进行转换,以便每个值都是 bool 值,从而给出:

{attribute_1 : True,
attribute_2 : False,
attribute_3_foo : True,
attribute_4_5 : True}

(机器学习的一次性编码,以防有人关心我为什么要做这么奇怪的事情。将处理很多很多这样的字典......)。

我发现的一个可行的解决方案是通过字典进行 for 循环来寻找非 bool 值,并 (1) 创建新条目,然后 (2) 删除带有非 bool 键的任何内容。这很好,但它看起来不优雅并且内存效率低下,因为我的列表是内存中的新对象。有更好的方法吗?

# List loop to insert ('k,v in dict' won't let you add/delete items)
for x in list(sub_d.items()):
if type(x[1]) is not bool:
sub_d[x[0]+'_'+ str(x[1])] = True
del sub_d[x[0]]
PS。列表理解不起作用,因为我找不到一种方法来提供足够复杂的操作来完成这项工作。另外,我认为他们不会比我当前的解决方案有任何效率提升?

最佳答案

可以使用dict理解:

d = {k if isinstance(v, bool) else '{}_{}'.format(k, v): bool(v) 
for k, v in d.items()}

{'attribute_1': True,
'attribute_2': False,
'attribute_3_foo': True,
'attribute_4_5': True}

关于python - 在 for 循环中从字典中插入和删除——最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52460156/

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