好的,這個問題起初聽起來可能令人困惑,但我會盡我所能解釋我想學習的內容,以提高我的編程技能。
假設我有一個路徑,其中存在 6 個檔案夾,其中包含以下檔案影像:
顏色:
Amarillo.png Blanco.png Rojirosado.png Turquesa.png Verde_oscuro.png Zapote.png
庫爾波:
Cuerpo_cangrejo.png
方多:
海洋.png
奧喬斯:
Antenas.png Pico.png Verticales.png
品薩:
Pinzitas.png Pinzotas.png Pinzota_pinzita.png
普阿斯:
Arena.png Marron.png Purpura.png Verde.png
現在,我希望將上述資訊存盤在字典中以供進一步使用,因此我在前面提到的檔案夾所在的同一路徑中運行以下代碼:
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)
所以在編譯上面的程式后,我得到了我的字典:

但問題是:創建字典后,如何讓用戶決定在哪些陣列中添加“無”字串作為新值(即不替換當前值),這意味著,例如,如果用戶想要僅將“ 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395693.html
下一篇:將字典轉換為多索引資料框
