我有以下输入数据,需要存储在适当的数据结构中。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其中应该提供以下信息。我已经按照以下方式使用 python3 实现了,其时间复杂度为 O(n),其中 n 是文件中的行数。是否有其他有效的解决方案来存储上述信息。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
添加回答
举报
0/150
提交
取消