gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:46 33 4
gpt4 key购买 nike

这里是 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...;禀赋=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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com