AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78312055
Accepted
Saeed
Saeed
Asked: 2024-04-12 01:19:58 +0800 CST2024-04-12 01:19:58 +0800 CST 2024-04-12 01:19:58 +0800 CST

如何根据字典列表的值写入不同的文件并连接 for 循环和三个字典列表

  • 772

首先,如果问题太长,我很抱歉。我试图包含最少的数据,但那是我可以添加的。

这些是我的清单:

products_income = [
    {'client_group': 'A', 'count': 2, 'product': 'A', 'monthly_income': 370},
    {'client_group': 'B', 'count': 1, 'product': 'B', 'monthly_income': 215},
    {'client_group': 'C', 'count': 3, 'product': 'C', 'monthly_income': 495},
    {'client_group': 'A', 'count': 2, 'product': 'D', 'monthly_income': 304},
    {'client_group': 'B', 'count': 1, 'product': 'E', 'monthly_income': 110},
    {'client_group': 'B', 'count': 2, 'product': 'F', 'monthly_income': 560},
    {'client_group': 'A', 'count': 1, 'product': 'G', 'monthly_income': 196},
    ]

client_package = [
    {'client_group': 'A', 'total_income': 870},
    {'client_group': 'B', 'total_income': 885},
    {'client_group': 'C', 'total_income': 495}
]

client_group_user_counts = {
    'A': ['user1', 'user2', 'user3', 'user4', 'user5'], # 5 users
    'B': ['user21', 'user22', 'user23', 'user24'], # 4 users
    'C': ['user41', 'user42', 'user43'], # 3 users
}

这些是我商店的输出,这是写入“ client_group.txt”调用的不同文件的预期输出:

A.txt:

group A has 2 product A, monthly income is 370.
group A has 2 product D, monthly income is 304.
group A has 1 product G, monthly income is 196.

group A total income is 870.

group A has total 5 users, and this is its users:
user1
user2
user3
user4
user5

B.txt:

group B has 1 product B, monthly income is 215.
group B has 1 product E, monthly income is 110.
group B has 2 product F, monthly income is 560.

group B total income is 885.

group B has total 4 users, and this is its users

user21
user22
user23
user24

C.txt:

group C has 3 product C, monthly income is 495.

group C total income is 495.

group C has total 3 users, and this is its users:
user41
user42
user43

这是我当前的代码,我尚未达到预期的输出(实际上,除了我的代码的其他问题之外,目前我不知道如何在这种情况下写入单独的文件):

# I added this function, because I had error in the last line of next code block inside the `f-string`, so I thought that could be a workaround for this
def to_join():
    return '\n'.join(client_group_user_counts[user])

for product in products_income:
    for client in client_package:
        for user in client_group_user_counts:
            if product['client_group'] == client['client_group'] == user:
                print(f"""group {product['client_group']} has {product['count']} product {product['product']}, monthly income is {product['monthly_income']}.
total income is {client['total_income']}.
group {product['client_group']} has total {len(client_group_user_counts[user])} users, and this is its users:
{to_join()}
""")

这是当前输出:

group A has 2 product A, monthly income is 370.
group A total income is 870.
group A has total 5 users, and this is its users:
user1
user2
user3
user4
user5

group B has 1 product B, monthly income is 215.
group B total income is 885.
group B has total 4 users, and this is its users:
user21
user22
user23
user24

group C has 3 product C, monthly income is 495.
group C total income is 495.
group C has total 3 users, and this is its users:
user41
user42
user43

group A has 2 product D, monthly income is 304.
group A total income is 870.
group A has total 5 users, and this is its users:
user1
user2
user3
user4
user5

group B has 1 product E, monthly income is 110.
group B total income is 885.
group B has total 4 users, and this is its users:
user21
user22
user23
user24

group B has 2 product F, monthly income is 560.
group B total income is 885.
group B has total 4 users, and this is its users:
user21
user22
user23
user24

group A has 1 product G, monthly income is 196.
group A total income is 870.
group A has total 5 users, and this is its users:
user1
user2
user3
user4
user5
python
  • 4 4 个回答
  • 39 Views

4 个回答

  • Voted
  1. inspectorG4dget
    2024-04-12T01:43:32+08:002024-04-12T01:43:32+08:00

    逻辑如下:

    您已经拥有 中的所有组名称client_group_user_counts。我们将使用它来生成一堆文件。我们还将把组名映射到文件名(这个程序并不完全需要,但这是一个很好的选择,以防万一您的逻辑在以后变得更加复杂)。

    然后,我们将迭代products_income. 我们使用值查找输出文件名group_name并写入格式化的记录。

    一旦我们写完所有记录,我们将迭代client_package写出总收入。但是等一下,我们将重新格式化该字典,以便键是组名称,值是总收入 - 这只会节省我们一些查找步骤。

    最后,我们将迭代client_group_user_counts。由于键已经是组名称,因此我们可以使用它们来查找输出文件。然后我们只需要将用户名本身写入输出文件

    这是代码:

    # create all the output files
    outfiles = {k: open(f"{k}.txt", 'w') for k in client_group_user_counts}
    
    # turn client_package into a dict for easier access
    client_package = {row['client_group']: row['total_income'] for row in client_package}
    
    # write everything to the correct files
    for row in products_income:
        cgroup = row['client_group']
        prodCount = row['count']
        prodName = row['product']
        income = row['monthly_income']
    
        outfile = outfiles[cgroup]
        outfile.write(f"group {cgroup} has {prodCount} product {prodName}, monthly income is {income}.\n")
    
    # add the additional space
    for outfile in outfiles.values():
        outfile.write('\n')
    
    # write the total income summary
    for group, income in client_package.items():
        outfiles[group].write(f"group {group} total income is {income}.\n\n")
    
    # add the users
    for group,users in client_group_user_counts.items():
        outfiles[group].write(f"group {group} has total {len(users)} users, and this is its users:\n")
        for user in users:
            outfiles[group].write(f"{user}\n")
    
    # close the files
    for outfile in outfiles.values():
        outfile.close()
    
    • 2
  2. mozway
    2024-04-12T01:55:49+08:002024-04-12T01:55:49+08:00

    我会首先重新编写字典,以避免以后忽略它们。

    然后对每个键仅循环一次并使用以下语句打开文件with:

    products = {}
    for d in products_income:
        (products
         .setdefault(d['client_group'], []) 
         .append('group {client_group} has {count} product {product}, monthly income is {monthly_income}.'.format(**d))
        )
    packages = {}
    for d in client_package:
        (packages
         .setdefault(d['client_group'], []) 
         .append('group {client_group} total income is {total_income}.'.format(**d))
        )
    
    for group, users in client_group_user_counts.items():
        with open(f'{group}.txt', 'w') as f:
            f.write('\n'.join(products[group])+'\n\n')
            f.write('\n'.join(packages[group])+'\n\n')
            f.write(f'group {group} has total {len(users)} users, and this is its users:\n')
            f.write('\n'.join(users))
    

    例子A.txt:

    group A has 2 product A, monthly income is 370.
    group A has 2 product D, monthly income is 304.
    group A has 1 product G, monthly income is 196.
    
    group A total income is 870.
    
    group A has total 5 users, and this is its users:
    user1
    user2
    user3
    user4
    user5
    
    • 2
  3. Best Answer
    JonSG
    2024-04-12T01:43:19+08:002024-04-12T01:43:19+08:00

    由于结果是按“组 ID”聚合的,因此您需要client_group_user_counts首先进行迭代。这还允许您获取open()特定于当前“组 ID”的文件

    这可能需要一些重构,但它应该给你一个想法

    鉴于:

    products_income = [
        {'client_group': 'A', 'count': 2, 'product': 'A', 'monthly_income': 370},
        {'client_group': 'B', 'count': 1, 'product': 'B', 'monthly_income': 215},
        {'client_group': 'C', 'count': 3, 'product': 'C', 'monthly_income': 495},
        {'client_group': 'A', 'count': 2, 'product': 'D', 'monthly_income': 304},
        {'client_group': 'B', 'count': 1, 'product': 'E', 'monthly_income': 110},
        {'client_group': 'B', 'count': 2, 'product': 'F', 'monthly_income': 560},
        {'client_group': 'A', 'count': 1, 'product': 'G', 'monthly_income': 196},
        ]
    
    client_package = [
        {'client_group': 'A', 'total_income': 870},
        {'client_group': 'B', 'total_income': 885},
        {'client_group': 'C', 'total_income': 495}
    ]
    
    client_group_user_counts = {
        'A': ['user1', 'user2', 'user3', 'user4', 'user5'], # 5 users
        'B': ['user21', 'user22', 'user23', 'user24'], # 4 users
        'C': ['user41', 'user42', 'user43'], # 3 users
    }
    

    尝试:

    for group_key, group_users in client_group_user_counts.items():
        packages = [row for row in client_package if row["client_group"] == group_key]
        products = [row for row in products_income if row["client_group"] == group_key]
        with open(f"{group_key}.txt", "w", encoding="utf-8", newline="") as file_out:
            for product in products:
                file_out.write(f"group {group_key} has {product['count']} product {product['product']}, monthly income is {product['monthly_income']}.\n")
            file_out.write("\n")
            file_out.write(f"group {group_key} total income is {packages[0]['total_income']}.\n")
            file_out.write("\n")
            file_out.write(f"group {group_key} has total {len(group_users)} users, and this is its users:\n")
            for user in group_users:
                file_out.write(f"{user}\n")
    
    • 1
  4. Mohsen_Fatemi
    2024-04-12T01:45:37+08:002024-04-12T01:45:37+08:00

    不知道我是否理解你的程序结构,如果我错了,请纠正我的。由于您拥有组,因此client_group_user_counts您可以从其键中获取所有组。

    groups = client_group_user_counts.keys()
    

    现在您已经拥有了所有组,您可以迭代组并打印上面提到的内容。

    for group in groups :
        for product in products_income:
            if product['client_group']==group:
                print(f"group {group} has {product['count']} product {product['product']}, monthly income is {product['monthly_income']}.")
        for package in client_package:
            if package['client_group']==group:
                print(f"group {group} total income is {package['total_income']}.")
        print(f"group {group} has total {len(client_group_user_counts[group])} users, and this is its users:")
        print('\n'.join(client_group_user_counts[group]))
        print()
    

    但通常建议使用 pandas 等库来完成更复杂的任务。

    • 1

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve