Skip to main content
 首页 » 编程设计

python之生成任意数量的 if 语句和字典索引

2024年10月01日8zlslch

我有一个问题。如何执行多个 if 语句同时更改字典索引的数量?我认为我的代码很好地总结了我想要发生的事情,但我会进一步解释。使用 dict = {"Hi":{"Hello":{"Greetings":"Goodbye"}}} 我想要一组 if 语句能够访问该字典中的每个点而无需分别键入每一个。 所以对于这个,

If level == 1: 
    print(dict["Hi"]) 
If level == 2: 
    print(dict["Hi"]["Hello"]) 
If level == 3: 
    print(dict["Hi"]["Hello"]["Greetings"]) 

一段代码示例:

E = {"C:":{"Desktop.fld":{"Hello.txt":{"Content":"Hello, World"}}}} 
 
 
def PATH_APPEND(path, item, location, content): 
    if len(location) == 1: 
        E[location[0]] = item 
        E[location[0]][item] = content 
    if len(location) == 2: 
        E[location[0]][location[1]] = item 
        E[location[0]][location[1]][item] = content 
    if len(location) == 3: 
        E[location[0]][location[1]][location[2]][item] = content 
    # ... and so on 
 
PATH_APPEND(E, "Hi.txt", ["C:","Desktop.fld"], "Hi There, World") 
print(E) 
#{"C:":{"Desktop.fld":{ ... , "Hi.txt":{"Content":"Hi There, World"}}}} 

我在运行我的示例时遇到错误,但我认为它很好地理解了这一点。

请您参考如下方法:

对于此任务,您不需要任何 if 语句,您可以使用一个简单的 for 循环来进入您的嵌套字典。

from pprint import pprint 
 
def path_append(path, item, location, content): 
    for k in location: 
        path = path[k] 
    path[item] = {"Content": content} 
 
# test 
 
E = {"C:":{"Desktop.fld":{"Hello.txt":{"Content":"Hello, World"}}}}     
print('old') 
pprint(E) 
 
path_append(E, "Hi.txt", ["C:", "Desktop.fld"], "Hi There, World") 
print('\nnew') 
pprint(E) 

输出

old 
{'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'}}}} 
 
new 
{'C:': {'Desktop.fld': {'Hello.txt': {'Content': 'Hello, World'}, 
                        'Hi.txt': {'Content': 'Hi There, World'}}}} 

顺便说一句,你不应该使用 dict 作为变量名,因为它隐藏了内置的 dict 类型。

此外,在 Python 中,通常对普通变量和函数名称使用小写字母。所有大写字母用于常量,大写名称用于类。请参阅PEP 8 -- Style Guide for Python Code了解更多详情。

我还注意到您问题开头的代码块使用 If 而不是正确的 if 语法,但也许这应该是伪代码。