我有以下輸入數(shù)據(jù),需要存儲在適當(dāng)?shù)臄?shù)據(jù)結(jié)構(gòu)中。ElectronicsElectronics > Arcade EquipmentElectronics > Arcade Equipment > Basketball Arcade GamesElectronics > Arcade Equipment > Video Game Arcade CabinetsElectronics > AudioElectronics > Audio > Audio AccessoriesElectronics > Audio > Audio Accessories > Audio & Video Receiver AccessoriesElectronics > Audio > Audio Accessories > Headphone & Headset AccessoriesElectronics > Audio > Audio Accessories > Headphone & Headset Accessories > Headphone Cushions & TipsApparel & Accessories > Clothing > Activewear > Hunting Clothing > Hunting & Tactical PantsApparel & Accessories > Clothing > Activewear > Martial Arts ShortsApparel & Accessories > Clothing > Activewear > Motorcycle Protective ClothingApparel & Accessories > Clothing > Baby & Toddler ClothingAnimals & Pet Supplies > Pet Supplies > Pet Grooming Supplies > Pet Nail Polish其中應(yīng)該提供以下信息。我已經(jīng)按照以下方式使用 python3 實(shí)現(xiàn)了,其時間復(fù)雜度為 O(n),其中 n 是文件中的行數(shù)。是否有其他有效的解決方案來存儲上述信息。def get_data(file_path): try: if not os.path.exists(file_path): # check file exist or not raise FileNotFoundError except FileNotFoundError: print('please provide valid file path') exit() inventory = {} with open(file=file_path, mode='r', encoding='utf-8') as file_descr: try: for line in file_descr: line = line.strip() llist = line.split('>') # list of keys for i in range(1, len(llist) + 1): # check entry of each possible key in inventory key = ('>'.join(llist[:i])).strip() if inventory.get(key): inventory[key] += 1 else: inventory[key] = 1 except Exception as e: print('not able to read content', e) exit() return inventory
添加回答
舉報(bào)
0/150
提交
取消