繁体   English   中英

如何在 python 的字典中替换字符

[英]How do I replace a char in a dict in python

我在字典中有这棵树:

tree = {"'name': 'mass_index', 'direction': '>=', 'threshold': '27.8', 'children'": [0.0,
  {"'name': 'age', 'direction': '>=', 'threshold': '30.0', 'children'": [{"'name': 'mass_index', 'direction': '>=', 'threshold': '41.5', 'children'": [0.0,
      1.0]},
    1.0]}]}

type(tree)
dict

如何将0.0替换为'{false}'1.0替换为'{true}'并删除所有" 。我找不到如何替换 dict 中的字符而不是整个 dict 值。在字符串中很容易我可以只做value = value.replace('1.0', 'True')value = value.replace('"', '')但如何在字典中做到这一点? 我将非常感谢任何帮助。

编辑(这是产生字典的部分):

feature_name = COLUMN_HEADERS[split_column]
    type_of_feature = FEATURE_TYPES[split_column]
    if type_of_feature == "continuous":
        question = "'cues': '{}', 'directions': '>=', 'thresholds': '{}', 'children'".format(feature_name, split_value)
        
    # feature is categorical
    else:
        question = "'cues': '{}', 'directions': '>=', 'thresholds': '{}', 'children'".format(feature_name, split_value)
    
    # instantiate sub-tree
    sub_tree = {question: []}

如何将 dict 转换为字符串,然后使用regex替换。 然后,将其转换回字典。

样本:

import re
tree = {"'name': 'mass_index', 'direction': '>=', 'threshold': '27.8', 'children'": [0.0,
{"'name': 'age', 'direction': '>=', 'threshold': '30.0', 'children'": [{"'name': 'mass_index', 'direction': '>=', 'threshold': '41.5', 'children'": [0.0,
      1.0]},
    1.0]}]}

treeStr = str(tree)
    
treeStr = re.sub(r'\[0.0,', '[\'false\',', treeStr)
treeStr  = re.sub(r'\, 0.0]', ', \'false\']', treeStr)

treeStr = re.sub(r'\[1.0,', '[\'true\',', treeStr)
treeStr = re.sub(r'\, 1.0]', ', \'true\']', treeStr) 
    
import ast
treeDict = ast.literal_eval(treeStr)

type(treeDict)
print(treeDict)

尝试从一开始就为你的树创建一个字典,而不是使用str.format()

这应该允许您遍历您的 dict 并替换不需要的值。

feature_name = COLUMN_HEADERS[split_column]
type_of_feature = FEATURE_TYPES[split_column]
question = {'directions': '>='}
if type_of_feature == "continuous":
    question['cues'] = feature_name
    question['thresholds'] = split_value

# I can't see any reason why this if statement is here, but I'll leave it if there's other things you add
else:   # feature is categorical
    question['cues'] = feature_name
    question['thresholds'] = split_value
    
    # instantiate sub-tree
sub_tree = {question: []}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM