如何在Python循环中动态更新参数值?

2 投票
1 回答
1060 浏览
提问于 2025-04-16 03:44

我是个Python新手:

我正在用Python和Pysage写一个市场模拟程序,想要通过 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

我想知道,有没有一种简洁、符合Python风格的方法来运行这个函数,这样每次循环的时候,name、maxValuation、endowment和id的值都能变化,比如说 name="buyer002", name="buyer003"...; maxValuation=95, maxValuation=90...; endowment=450, endowment=400...; "buyer002", "buyer003"... 之类的。

我试过不同的for循环和列表推导式,但还没找到一个能动态更新函数参数的方法,而且没有遇到类型问题。

提前谢谢大家!

1 个回答

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

撰写回答