Python 嵌套循环中结果的唯一变量名称
有一个嵌套的for循环(2个外部和3个内部so共6个) 在内部循环中,我计算4个值-最小值、最大值、平均值和95% 对于列表中的浮动。 我需要为每个结果分配动态唯一变量名(最好是可读的名称)。 将有24个不同的结果,因此需要24个唯一的名称 希望将计算值指定给唯一变量名,如下所示 user1connmax、user1connmin、user1connavg、user1connpc95。 user1bytesmax、user1bytesmin、user1bytesavg、user1bytespc95 user2connmax、user2connmin、user2connavg、user2connpc95。 user2bytesmax、user2bytesmin、user2bytesavg、user2bytespc95 user3connmax、user3connmin、user3connavg、user3connpc95。Python 嵌套循环中结果的唯一变量名称,python,variables,dynamic,for-loop,Python,Variables,Dynamic,For Loop,有一个嵌套的for循环(2个外部和3个内部so共6个) 在内部循环中,我计算4个值-最小值、最大值、平均值和95% 对于列表中的浮动。 我需要为每个结果分配动态唯一变量名(最好是可读的名称)。 将有24个不同的结果,因此需要24个唯一的名称 希望将计算值指定给唯一变量名,如下所示 user1connmax、user1connmin、user1connavg、user1connpc95。 user1bytesmax、user1bytesmin、user1bytesavg、user1bytespc9
user3bytesmax、user3bytesmin、user3bytesavg、user3bytespc95如果我理解正确,您可以使用字典存储结果,并将键作为唯一键。对您所描述的内容的改进是将您对给定用户的所有价值存储在子目录下:
results = {}
key_prefix = "user"
i= 0
for item in your_list :
# your own logic
values = {
"connmax": the_value,
"connmin": the_value,
"connavg": the_value,
"connpc95": the_value,
"bytesmax": the_value,
"bytesmin": the_value,
"bytesavg": the_value,
"bytespc95": the_value,
}
key = key_prefix+str(i) # build the unique key
results[key] = values
i += 1 # increment i
# then, you can access values like this :
user1_values = results["user1"]
user1_connmax = user1_values['connmax']
# or, in short :
user1_connmax = results["user1"]["connmax"]
一个稍微复杂的例子:
import numpy
from collections import defaultdict
class User:
def __init__(self):
self.conn = []
self.bytes = []
def update(self, c, b):
self.conn .append(c)
self.bytes.append(b)
@property
def conn_min(self):
return min(self.conn)
@property
def conn_max(self):
return max(self.conn)
@property
def conn_avg(self):
return sum(self.conn, 0.) / (len(self.conn) or 1)
@property
def conn_95pct(self):
return numpy.percentile(self.conn, 95)
@property
def bytes_min(self):
return min(self.bytes)
@property
def bytes_max(self):
return max(self.bytes)
@property
def bytes_avg(self):
return sum(self.bytes, 0.) / (len(self.bytes) or 1)
@property
def bytes_95pct(self):
return numpy.percentile(self.bytes, 95)
def main():
users = defaultdict(User)
for user, conn, bytes in datastream:
users[user].update(conn, bytes)
# and then you retrieve the data like
user1connmax = users['user1'].conn_max
if __name__=="__main__":
main()
为什么不使用字典呢?不要使用动态变量名;使用dict和groupby。变量名是稍后在代码中使用,还是用于脱机代码生成或数据转储?如果要在代码中使用这些变量名,最好的方法是填充字典或列表(或容器的嵌套结构),而不是生成并使用变量名。它们将在代码中用于进一步计算,然后复制到数据库中。我试过字典,但没怎么用,所以我想一直都失败了。你是对的,Python对这类东西很好,其他很多东西也很好;)如果这对你有帮助,记得把这个答案标记为已接受。请注意,Hugh的anwser也可以工作,并且更易于维护和扩展,所以在接受我的anwser之前,您可能希望尝试一下。