2016-12-06 4 views
0

pythonで複数の辞書値を入力値から設定しようとしていますが、常にエラー通知が返されます。スクリプトで辞書を宣言するとうまく動作します。だから私は試してみました:入力値から複数の辞書値を設定しますか?

adj=defaultdict(list) 

iteration=input("the number of edges that constructed: ") 
for i in range (0,int(iteration)): 
    #A(vertices1) B(vertices2) W(weight) 
    abw=input("A B W : ") 
    if len(abw)==1: 
     a=int(abw) 
     valueBW=(None) 
     if a in adj: 
      adj[a].append(()) 
     else: 
      adj[a].append(()) 
      #dict.fromkeys(a,None) 
    else: 
     a,b,w=abw.split(' ') 
     a=int(a) 
     valueBW=(int(b),int(w)) 
     if a in adj: 
      adj[a].append(valueBW) 
     else: 
      #adj.update({a : [(int(b),int(w))]}) 
      adj[a].append(valueBW) 

これは入力例です。私はコードでそれを宣言した場合

the number of edges that constructed: 8 
A B W : 0 1 4 
A B W : 0 3 8 
A B W : 1 4 1 
A B W : 1 2 2 
A B W : 4 2 3 
A B W : 2 5 3 
A B W : 3 4 2 
A B W : 5 

これは辞書です:

adj = { 
    0: [(1, 4),(3, 8)], 
    1: [(4, 1),(2, 2)], 
    4: [(2, 3)], 
    2: [(5, 3)], 
    3: [(4, 2)], 
    5: [], 
    } 

は、私のコードの右ましたか?

+1

エラーは何ですか? –

+0

エラーが発生した場合は、トレースバック全体を投稿してください。 –

+0

よろしくお願いいたします。幸いにも私の問題はあなたの優しさのために –

答えて

0

それはあなたが何を望むかあなたの質問から完全には明らかではないのですが、私は、これはあなたが後にしているものであることをを信じ:あなたの提供された入力を使用して

# Always show your imports - we don't know if 
# you got defaultdict from here or somewhere else 
from collections import defaultdict 

adj=defaultdict(list) 

iteration=input("the number of edges that constructed: ") 

# You can omit the start if it's zero. 
# and if you're not using the variable, 
# indicate that by using `_` as your name 
for _ in range (int(iteration)): 
    #A(vertices1) B(vertices2) W(weight) 
    abw=input("A B W : ") 
    if len(abw)==1: 
     a=int(abw) 
     # Don't append anything 
     # just access it so that 
     # it exists. 
     adj[a] 
    else: 
     # By default, `.split()` uses any whitespace. 
     # This makes `1  2 3` work just fine. 
     a,b,w=abw.split() 
     a=int(a) 
     valueBW=(int(b),int(w)) 
     adj[a].append(valueBW) 

、これは私を与える:

{0: [(1, 4), (3, 8)], 
1: [(4, 1), (2, 2)], 
2: [(5, 3)], 
3: [(4, 2)], 
4: [(2, 3)], 
5: []} 

予想される出力のようです。辞書は発注されていないので、このように表示するには:

import pprint 

pprint.pprint(adj) 
+0

おかげで解決されています。今問題が解決されました –

+0

@HanifKhこれで問題が解決した場合は、左のチェックマーク「<----」をクリックして答えをマークしてください。それが*本当に役に立つなら、あなたもアップヴォートすることができます。 –

関連する問題