Python:基于一个键和子键构建一个字典列表,并根据名称、区域、区域总数和总计对结果进行汇总
我刚刚开始自学Python,目前仍在学习。我几乎没有编程经验。为了自学,我提出了以下问题。问题如下 我有3个卖家,他们在多个地区销售商品。我想知道他们每个地区的销售额,每个地区每个人的总销售额,以及他们所有人的总销售额 我有以下数据,我从一个txt文件中读取 姓名、地区、金额 文件按名称排序,但不按区域排序Python:基于一个键和子键构建一个字典列表,并根据名称、区域、区域总数和总计对结果进行汇总,python,Python,我刚刚开始自学Python,目前仍在学习。我几乎没有编程经验。为了自学,我提出了以下问题。问题如下 我有3个卖家,他们在多个地区销售商品。我想知道他们每个地区的销售额,每个地区每个人的总销售额,以及他们所有人的总销售额 我有以下数据,我从一个txt文件中读取 姓名、地区、金额 文件按名称排序,但不按区域排序 该名称可以是约翰、彼得或保罗三个值中的任意一个 该文件可能只包含其中一个或全部 对于每个人来说,他可能已经在1到x个地区销售了产品 对于每个地区,他可能销售了1到x件物品 在这个阶段,我
- 该名称可以是约翰、彼得或保罗三个值中的任意一个
- 该文件可能只包含其中一个或全部
- 对于每个人来说,他可能已经在1到x个地区销售了产品
- 对于每个地区,他可能销售了1到x件物品
{'John': {'r2': 55}, 'Peter': {'r1': 10, 'r2': 34, 'r3': 11}}
一种更面向对象的方法可能是为每个人和区域等创建单独的对象,但对于您正在尝试做的事情来说,这可能是过分的
根据要在事务中读取并填充这些数据结构的代码的外观,您可以执行以下操作:
# read in the transactions
with open('blah.txt') as file_obj:
raw_data = file_obj.readlines()
inventory = {} # initialize your outer dictionary
# parse the transactions and update the inventory
for line in raw_data:
if not line.strip():
continue
name, region, amount = line.strip().split()
# is r2 the same as R2?
region = region.lower()
# we'd like to manipulate amount as a number not a string
amount = float(amount)
# create a new inner dictionary for this name, if not one already
if not name in inventory:
inventory[name] = {}
# update the total for that region for that name
inventory[name][region] = inventory[name].get(region, 0) + amount
# with the data stored this way, you can easily query
# or calculate any totals you want, e.g.
def total_per_person_per_region(inv, name, region):
return inv[name][region]
def total_per_person(inv, name):
return sum(inv[name].values())
def grand_total(inv):
return sum(total_per_person(inv, name) for name in inv)
你不能像那样跳进python。在解决更大的问题之前,你需要先学习基础知识。我推荐免费的在线pdf,先试试看。一旦你陷入困境,查一下,再试一次。一旦你再次陷入困境,可以查找,也许可以在这里提问,再试一次。但是,对于这类初学者问题,可能非常适合。感谢链接AndrewGrant。事实证明这很有用。谢谢柠檬头,你给了我我想要的东西。非常感谢。
# read in the transactions
with open('blah.txt') as file_obj:
raw_data = file_obj.readlines()
inventory = {} # initialize your outer dictionary
# parse the transactions and update the inventory
for line in raw_data:
if not line.strip():
continue
name, region, amount = line.strip().split()
# is r2 the same as R2?
region = region.lower()
# we'd like to manipulate amount as a number not a string
amount = float(amount)
# create a new inner dictionary for this name, if not one already
if not name in inventory:
inventory[name] = {}
# update the total for that region for that name
inventory[name][region] = inventory[name].get(region, 0) + amount
# with the data stored this way, you can easily query
# or calculate any totals you want, e.g.
def total_per_person_per_region(inv, name, region):
return inv[name][region]
def total_per_person(inv, name):
return sum(inv[name].values())
def grand_total(inv):
return sum(total_per_person(inv, name) for name in inv)