我有一個txt文件的格式如下列表:創建列表的字典文件
Shoes, Nike, Addias, Puma,...other brand names
Pants, Dockers, Levis,...other brand names
Watches, Timex, Tiesto,...other brand names
如何把這些變成字典這樣的格式: 詞典= {鞋:耐克, Addias,彪馬,.....] 褲子:[碼頭工人,李維斯.....] 腕錶:[天美時,鐵斯托,.....] }
如何做到這一點的一個循環而不是手動輸入。
我曾嘗試
clothes=open('clothes.txt').readlines()
clothing=[]
stuff=[]
for line in clothes:
items=line.replace("\n","").split(',')
clothing.append(items[0])
stuff.append(items[1:])
Clothing:{}
for d in clothing:
Clothing[d]= [f for f in stuff]
1)genexpr會更好一些,2)迭代文件而不是分割(然後是'line.rstrip()')。否則,很好的答案。 – nneonneo
你的意思是類似'(line.rstrip()。split(',')for line in open('clothes.txt')。readlines())'? – Antimony
是的,除了你可以離開'.readlines'。 – nneonneo