我有一個筆記檔案,我試圖將其轉換為字典。我讓腳本正常作業,但在有重復值時無法輸出我正在尋找的資料。
簡而言之,按照下面的 # 分隔的檔案命令或注釋。我使用該串列并用# 分隔第一列“鍵”,其余的是注釋或定義。然后我檢查我正在尋找的魔法詞,決議它匹配它然后輸出。
抽認卡檔案如下
> car # automobile 4 wheels and run
> washington dc # the capital of United States
> fedora # an operating distro
> cat file # reads the file
> car nissan # altima
> car nissan # altima ## first car
> car nissan # maxima
> car nissan # rougue
flashcard_dict = dict()
flashcard_file = open('FlashCards','r')
enter = input("Searching nemo: ")
firstcolumn_str_list = list()
for x in flashcard_file:
flashcard_sprint = x.strip()
flascard_clean = flashcard_sprint.split("#",1)
firstcolumn_str = flascard_clean[0]
firstcolumn = firstcolumn_str.strip()
firstcolumn_str_list.append(firstcolumn)
secondcolumn = flascard_clean[1]
flashcard_dict[firstcolumn] = secondcolumn
print
print ("###" * 3)
lista = list()
# this is version 4 - where lambda works but fails as it matches the string in all words.
# so if the word is "es" all patterns are matched that has "es" AND NOT the specific word
filter_object = filter(lambda a: enter in a, firstcolumn_str_list)
for x in filter_object:
lista.append(x)
print (lista)
cc = 0
if cc < len(lista):
for lambdatodictmatch in lista:
if lambdatodictmatch in flashcard_dict:
print (flashcard_dict[lambdatodictmatch])
else:
print ("NONEsense... nothing here")
else:
print ("NONEsense... nothing here")
它再次起作用,但是當我搜索汽車 nissan 時。我得到四個回應,但我只得到最后一個“rogue”輸出,或者我得到 4 個重復回應“rogue”。
實作這一目標的最佳方法是什么?
uj5u.com熱心網友回復:
如果您可能有重復的元素,那么您應該始終使用串列來保留單個值
if firstcolumn not in flashcard_dict:
flashcard_dict[firstcolumn] = []
firstcolumn[firstcolumn].append(secondcolumn)
代替
flashcard_dict[firstcolumn] = secondcolumn
編輯:
具有其他更改的完整作業代碼
- 首先,我為變數使用更短且更易讀的名稱,
- 我在開始時讀取檔案,然后使用回圈請求不同的卡。
- 我添加了命令
!keys來顯示所有鍵,并!exit退出回圈并完成程式, list(sorted(flashcards.keys()))給出字典中的所有鍵而不重復值(并排序)
我io只用來模擬記憶體中的檔案 - 所以每個人都可以簡單地復制和運行這段代碼(不創建檔案FlashCards)但你應該使用open(...)
text = '''car # automobile 4 wheels and run
washington dc # the capital of United States
fedora # an operating distro
cat file # reads the file
car nissan # altima
car nissan # altima ## first car
car nissan # maxima
car nissan # rougue
'''
import io
# --- constansts ---
DEBUG = True
# --- functions ---
def read_data(filename='FlashCards'):
if DEBUG:
print('[DEBUG] reading file')
flashcards = dict() # with `s` at the end because it keeps many flashcards
#file_handler = open(filename)
file_handler = io.StringIO(text)
for line in file_handler:
line = line.strip()
parts = line.split("#", 1)
key = parts[0].strip()
value = parts[1].strip()
if key not in flashcards:
flashcards[key] = []
flashcards[key].append(value)
all_keys = list(sorted(flashcards.keys()))
return flashcards, all_keys
# --- main ---
# - before loop -
# because words `key` and `keys` are very similar and it is easy to make mistake in code - so I added prefix `all_`
flashcards, all_keys = read_data()
print("#########")
# - loop -
while True:
print() # empty line to make output more readable
enter = input("Searching nemo (or command: !keys, !exit): ").strip().lower()
print() # empty line to make output more readable
if enter == '!exit':
break
elif enter == '!keys':
#print( "\n".join(all_keys) )
for key in all_keys:
print('key>', key)
elif enter.startswith('!'):
print('unknown command:', enter)
else:
# keys which have `enter` only at
#selected_keys = list(filter(lambda text: text.startswith(enter), all_keys))
# keys which have `enter` in any place (at the beginning, in the middle, at the end)
selected_keys = list(filter(lambda text: enter in text, all_keys))
print('selected_keys:', selected_keys)
if selected_keys: # instead of `0 < len(selected_keys)`
for key in selected_keys:
# `selected_keys` has to exist in `flashcards` so there is no need to check if `key` exists in `flashcards`
print(key, '=>', flashcards[key])
else:
print("NONEsense... nothing here")
# - after loop -
print('bye')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476901.html
上一篇:std::unordered_map::clear()是否會比std::map::clear()慢,因為清除操作在前者中“繼續”?
