这里是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"...;最大估价=95, 最大估价=90...;捐赠=450,捐赠=400...; “buyer002”、“buyer003”...
等等。
我尝试了不同的 for 循环和列表推导式,但尚未找到一种方法来动态更新函数参数而不遇到类型问题。
提前致谢!
最佳答案
您可以将 names
、maxValuations
和 endowments
准备为列表(或迭代器),然后使用 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
关于python - 如何动态更新Python循环中参数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3646142/