嵌套循环中结果的唯一变量名称

时间:2014-01-29 19:45:01

标签: python variables dynamic for-loop

有一个嵌套的for循环(2个外部和3个内部所以总共6个) 在内循环中,我计算4个值 - min,max,averages和95percentile 从列表中浮动。 我需要为每个结果分配动态唯一变量名(最好是可读名称)。 将有24种不同的结果,因此需要24个独特的名称。

希望将计算值分配给唯一变量名,如下所示。

user1connmax,user1connmin,user1connavg,user1connpc95。 user1bytesmax,user1bytesmin,user1bytesavg,user1bytespc95 user2connmax,user2connmin,user2connavg,user2connpc95。 user2bytesmax,user2bytesmin,user2bytesavg,user2bytespc95 user3connmax,user3connmin,user3connavg,user3connpc95。 user3bytesmax,user3bytesmin,user3bytesavg,user3bytespc95

2 个答案:

答案 0 :(得分:1)

一个稍微复杂的例子:

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()

答案 1 :(得分:0)

如果我理解正确,您可以使用词典存储结果,并将密钥作为唯一键。根据您描述的内容,您将在一个子词典下为给定用户存储您的所有价值:

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"]