3

txt ファイルに次の形式のリストがあります。

Shoes, Nike, Addias, Puma,...other brand names 
Pants, Dockers, Levis,...other brand names
Watches, Timex, Tiesto,...other brand names

これらを次の形式で辞書に入れる方法: dictionary={Shoes: [Nike, Addias, Puma,.....] Pants: [Dockers, Levis.....] Watches:[Timex, Tiesto,... ..] }

手動入力ではなく for ループでこれを行う方法。

私が試してみました

       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]
4

4 に答える 4

3

これがより簡潔な方法ですが、読みやすくするために少し分割することをお勧めします。

wordlines = [line.split(', ') for line in open('clothes.txt').read().split('\n')]
d = {w[0]:w[1:] for w in wordlines}
于 2012-10-23T05:21:23.810 に答える
2

どうですか:

file = open('clothes.txt')
clothing = {}
for line in file:
    items = [item.strip() for item in line.split(",")]
    clothing[items[0]] = items[1:] 
于 2012-10-23T05:19:59.340 に答える
1

これを試してみてください。改行を置き換える必要がなくなり、非常にシンプルですが効果的です。

clothes = {}
with open('clothes.txt', 'r', newline = '/r/n') as clothesfile:
    for line in clothesfile:
        key = line.split(',')[0]
        value = line.split(',')[1:]
        clothes[key] = value

'with' ステートメントは、辞書を実装するコードが実行された後に、ファイル リーダーが確実に閉じられるようにします。そこから辞書を思う存分使えます!

于 2012-10-23T06:33:41.797 に答える
0

リスト内包表記を使用すると、次のことができます。

clothes=[line.strip() for line in open('clothes.txt').readlines()]
clothingDict = {}
for line in clothes:
  arr = line.split(",")
  clothingDict[arr[0]] = [arr[i] for i in range(1,len(arr))]
于 2012-10-23T05:23:07.080 に答える