Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用for循环创建字典列表_Python_Python 3.x - Fatal编程技术网

Python 使用for循环创建字典列表

Python 使用for循环创建字典列表,python,python-3.x,Python,Python 3.x,我正在尝试获取以下代码: dirpath = os.getcwd() path = f"{dirpath}/static/user_images/user_{user_id}" l = [] ratings_list = [] for filename in Path(path).glob('**/*.*'): file = os.path.basename(filename) query = text('SELECT * FROM ratings WHERE photo_nam

我正在尝试获取以下代码:

dirpath = os.getcwd()
path = f"{dirpath}/static/user_images/user_{user_id}"
l = []
ratings_list = []
for filename in Path(path).glob('**/*.*'):
    file = os.path.basename(filename)
    query = text('SELECT * FROM ratings WHERE photo_name = "{}" AND photo_user_id = {}'.format(file, user_id))
    resultproxy = db.session.execute(query)

    for row in resultproxy:
        l.append(row.rating)
        total_ratings_count = len(l)
        average = statistics.mean(l)
        lowest = min(l)
        highest = max(l)

        data = {
        file: average, 
        "min": lowest,
        "max": highest,
        "number_of_ratings": total_ratings_count
        }
        ratings_list.append(data)
输出一个字典列表,每个字典都有图像名称和最大、最小、平均评级; 比如:

[
{"image_name": avg_rating, "max": max_rating, "min": min_rating, "number_of_ratings": ratings_count},
{"image_name_2": avg_rating, "max": max_rating, "min": min_rating, "number_of_ratings": ratings_count},
{"image_name_3": avg_rating, "max": max_rating, "min": min_rating, "number_of_ratings": ratings_count},
]
相反,我得到的是每个图像重复的单个值(即,如果记录了4个评级,那么将有4个条目返回各自的评级,而不是平均值)

当我将数据项移出第二个for循环时,如下所示:

for filename in Path(path).glob('**/*.*'):
    file = os.path.basename(filename)
    query = text('SELECT * FROM ratings WHERE photo_name = "{}" AND photo_user_id = {}'.format(file, user_id))
    resultproxy = db.session.execute(query)

    for row in resultproxy:
        l.append(row.rating)
    total_ratings_count = len(l)
    average = statistics.mean(l)
    lowest = min(l)
    highest = max(l)

    data = {
    file: average,
    "min": lowest,
    "max": highest,
    "number_of_ratings": total_ratings_count
    }
    ratings_list.append(data)

我得到错误
统计。统计错误:平均值至少需要一个数据点。当我打印(l)
时,它返回一个空列表。

好的,所以我发现最简单的方法是让sql做数学工作,这似乎可以减少复杂性。工作守则是:

    @classmethod
    def load_user_ratings(cls, user_id) -> dict:
        dirpath = os.getcwd()
        path = f"{dirpath}/static/user_images/user_{user_id}"
        d = {}
        ratings_list = []
        for filename in Path(path).glob('**/*.*'):
            file = os.path.basename(filename)
            sql = text('SELECT AVG(rating) as average, MAX(rating) as maximum, MIN(rating) as minimum FROM ratings '
                       'WHERE photo_name = "{}" AND photo_user_id = {}'.format(file, user_id))
            resultproxy = db.session.execute(sql)

            for row in resultproxy:
                for column, value in row.items():
                    # build up the dictionary
                    d = {**d, **{column: value}}
                    d.update({"image": file})
            ratings_list.append(d)
    return ratings_list
为清楚起见,
resultproxy
是一个sqlalchemy对象,它输出类似于

这道题的真正问题是在完成数学运算后,将结果正确地输入词典。将
ratings\u list.append(d)
移动到第二个for循环的外部,只要sql查询正在处理AVG/MIN/MAX,就可以完成这一操作。否则,您将得到一个
statistics.StatisticsError:mean需要至少一个数据点
错误,当在终端中打印时,显示初始列表为空,然后迭代填充


我认为这是有道理的,但我无法弄清楚如何让python正确处理这些数字。这是一个大补丁,因为我怀疑在某个时候我需要做更复杂的数学运算,这超出了SQL的能力。

如果您可以显示当前输出的外观,您需要提供一个解决方案,您可以添加
resultproxy
的输出吗?