2010-09-05 90 views
2

Python的新手在這裏:如何動態更新Python循環中參數的值?

我使用Pysage用Python寫一個市場模擬,並希望產生的代理任意數量(無論是買家或賣家)使用mgr.register_actor()功能,如下所示:

for name, maxValuation, endowment, id in xrange(5): 
    mgr.register_actor(Buyer(name="buyer001", maxValuation=100, endowment=500),"buyer001") 
    update name, maxValuation, endowment, id 

什麼是運行該函數調用的簡潔pythonic方法,以便每次運行循環時都會更改name,maxValuation,endowment和id的值,例如到name="buyer002", name="buyer003"...; maxValuation=95, maxValuation=90...; endowment=450, endowment=400...; "buyer002", "buyer003"...等等。

我已經嘗試了不同的for循環和列表解析,但還沒有找到一種方法來動態更新函數參數而不會遇到類型問題。

在此先感謝!

回答

4

可以準備namesmaxValuationsendowments作爲列表(或迭代器),然後使用zip到組對應的元件一起:

names=['buyer{i:0>3d}'.format(i=i) for i in range(1,6)] 
maxValuations=range(100,75,-5) 
endowments=range(500,250,-50) 
for name, maxValuation, endowment in zip(names,maxValuations,endowments): 
    mgr.register_actor(
     Buyer(name=name, maxValuation=maxValuation, endowment=endowment),name) 

關於格式字符串,'{i:0>3d}'

當我需要建立格式字符串時,我指的是這個「備忘單」:

http://docs.python.org/library/string.html#format-string-syntax 
replacement_field ::= "{" field_name ["!" conversion] [":" format_spec] "}" 
field_name  ::= (identifier|integer)("."attribute_name|"["element_index"]")* 
attribute_name ::= identifier 
element_index  ::= integer 
conversion  ::= "r" | "s" 
format_spec  ::= [[fill]align][sign][#][0][width][.precision][type] 
fill    ::= <a character other than '}'> 
align    ::= "<" | ">" | "=" | "^" 
         "=" forces the padding to be placed after the sign (if any) 
          but before the digits. (for numeric types) 
sign    ::= "+" | "-" | " " 
         " " places a leading space for positive numbers 
width    ::= integer 
precision   ::= integer 
type    ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | 
         "o" | "x" | "X" | "%" 

所以,它打破了這樣的:

field_name 
/
{i:0>3d} 
    \\\\ 
    \\\`-type ("d" means integer) 
     \\`-width 
     \`-alignment (">" means right adjust) 
     `-fill character 
+0

+1:我真的很喜歡的(相對)新的字符串格式()方法。由於傳統原因,我一直被困在2.5.x中,並且沒有在2.6/3.x中重新閱讀新文檔。謝謝! – 2010-09-05 13:57:21

+0

謝謝你,這個伎倆。我仍然在努力解決'{i:0> 3d}'是如何工作的,並且會閱讀格式規範迷你語言文檔。 – Tiresias 2010-09-05 14:55:30