拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何让用户将“无”添加到在Python字典中设定为特定键值的特定阵列?

如何让用户将“无”添加到在Python字典中设定为特定键值的特定阵列?

白鹭 - 2022-01-26 1962 0 0

好的,这个问题起初听起来可能令人困惑,但我会尽我所能解释我想学习的内容,以提高我的编程技能。

假设我有一个路径,其中存在 6 个档案夹,其中包含以下档案影像:

颜色:

库尔波:

方多:

奥乔斯:

品萨:

普阿斯:

现在,我希望将上述信息存盘在字典中以供进一步使用,因此我在前面提到的档案夹所在的同一路径中运行以下代码

import os
# Main method
the_dictionary_list = {}

for name in os.listdir("."):
    if os.path.isdir(name):
        path = os.path.basename(name)
        print(f'\u001b[45m{path}\033[0m')
        list_of_file_contents = os.listdir(path)
        print(f'\033[46m{list_of_file_contents}')
        the_dictionary_list[path] = list_of_file_contents
        print('\n')
print('\u001b[43mthe_dictionary_list:\033[0m')
print(the_dictionary_list)

所以在编译上面的程序后,我得到了我的字典:

如何让用户将“无”添加到在 Python 字典中设定为特定键值的特定阵列?

但问题是:创建字典后,如何让用户决定在哪些阵列中添加“”字符串作为新值(即不替换当前值),这意味着,例如,如果用户想要将“ None添加PuasArray 和PinzasArray,它会生成以下输出?:

the_dictionary_list: {
'Color': ['Amarillo.png', 'Blanco.png','Rojirosado.png', 'Turquesa.png', 'Verde_oscuro.png', 
'Zapote.png'],
'Cuerpo': ['Cuerpo_cangrejo.png'],
'Fondo': ['Oceano.png'], 
'Ojos': ['Antenas.png', 'Pico.png', 'Verticales.png'],
'Pinzas': ['None', 'Pinzitas.png', 'Pinzotas.png', 'Pinzota_pinzita.png'],
'Puas': ['None', 'Arena.png', 'Marron.png', 'Purpura.png', 'Verde.png']}

uj5u.com热心网友回复:

根据我的理解,您希望获取用户输入并插入None到每个键的前面。正如@robbo 提到的,您可以使用插入。其文本实作如下所示:

to_add = []
user_input = input("Which directory to add None to: ")

# Will exit when user gives null input
while user_input:
    if user_input in the_dictionary_list:
        to_add.append(user_input)
    else:
        print("Try again.")
    user_input = input("Which directory to add None to: ")

# Add to dictionary
for key in to_add:
    the_dictionary_list[key].insert(0, None)
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *