python - 如何动态更新Python循环中参数的值?

标签 python for-loop

这里是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 循环和列表推导式,但尚未找到一种方法来动态更新函数参数而不遇到类型问题。

提前致谢!

最佳答案

您可以将 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

关于python - 如何动态更新Python循环中参数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3646142/

相关文章:

python - 有没有办法使 Google Cloud Pub/Sub 架构字段成为可选字段?

c++ - 偶数行显示不正确,而奇数行显示正确

java - 如何有效地从 ArrayList 或字符串数​​组中删除所有空元素?

python - 组合两个不同数据帧的向量化 for 循环

python - 如何更改 lxml objectify 中子元素的顺序?

python ndarray 什么是返回值

python - 在python中转义mysql的单引号和双引号

python - Django 查询外键返回列表 "grouped by"

ruby - for循环的用法?

c++ - g++ 优化中断循环