2016-10-12 9 views
0

私は線形計画問題で作業する変数のリストを設定しようとしています。このためには、コードを大幅に短くて読みやすくするために、いくつかのインデックス値を使用したいと思います。これは私のリストを返しますPython3.5で変数を索引付けし、変数名に月を追加

from datetime import * 

months = ["Unknown", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] 

d={} 

for x in range(1,13): 
    d["string{0}".format(x)]=("Production in months[d]") 

print(d) 

{'string7': 'Production in months[d]', 'string8': 'Production in months[d]', 'string2': 'Production in months[d]', 'string9': 'Production in months[d]', 'string11': 'Production in months[d]', 'string6': 'Production in months[d]', 'string12': 'Production in months[d]', 'string3': 'Production in months[d]', 'string10': 'Production in months[d]', 'string4': 'Production in months[d]', 'string1': 'Production in months[d]', 'string5': 'Production in months[d]'} 

私はインデックス番号に対応し、数ヶ月[D]が印刷された月の名前を持っていると思います私がように何かをしようとしたのです私は 'string [i]'にいます。

+0

'd {" string {0} "。format(x)" = "{}"形式での書式(月[x]) 'または' d {"文字列{0}" .format(x)] = "Production in" + months [x] –

+0

ありがとうございました!トリックをしました – Jeroen

+0

私の答えを[受け入れ](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)としてマークしました。 –

答えて

0

用途:シンプルだし、あなたはすでにあなたのコード内で一度それを行っている

d["string{0}".format(x)]=("Production in %s" % months[d]) 
+0

これは残念なことに私のためには動作しません.. TypeErrorを与えます: – Jeroen

1

for x in range(1,13): 
    d["string{0}".format(x)]="Production in {}".format(months[x]) 

for key, value in d.items(): 
    print(key, value) 

出力:

string5 Production in May 
string4 Production in April 
string1 Production in January 
string2 Production in February 
string11 Production in November 
string9 Production in September 
string7 Production in July 
string8 Production in August 
string10 Production in October 
string3 Production in March 
string12 Production in December 
string6 Production in June 

注多分異なる順序います。また、format()引数のプレースホルダー内の位置を"Production in {}".format(months[x])のように指定しない場合は、引数が指定された順序で挿入されます。

関連する問題