我有一个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