查询和总计列表中的certian元素

时间:2018-06-07 10:55:54

标签: python list

所以我对python很新,我创建了一个如下所示的信息列表:

格式为日期,商店,总收入(当天)和交易(当天)

data = [[datetime.datetime(2012, 3, 1, 0), 'PizzaHut', 2839.60, 25], [datetime.datetime(2012, 12, 4, 0), 'Dominoes', 2839.60, 25], [datetime.datetime(2012, 11, 8, 0), 'Sals', 2839.60, 25], [datetime.datetime(2012, 6, 4, 0), 'Sals', 2839.60, 25], [datetime.datetime(2012, 8, 12, 0), 'PizzaHut', 2839.60, 25]

基本上我正在尝试的是查询某个商店的总收入。所以用户应该输入例如Sals'它将根据列表中的数据累计该商店的收入。这个问题可能有一个非常简单的解决方案,但我一直在网上四处寻找并决定是时候让我问你了。如果我可以得到一些关于它是如何工作的解释,这将真正帮助我,因为它可以帮助我发展我的知识!谢谢大家的贡献!

3 个答案:

答案 0 :(得分:3)

使用sum()

<强>实施例

import datetime
data = [[datetime.datetime(2012, 3, 1, 0), 'PizzaHut', 2839.60, 25], [datetime.datetime(2012, 12, 4, 0), 'Dominoes', 2839.60, 25], [datetime.datetime(2012, 11, 8, 0), 'Sals', 2839.60, 25], [datetime.datetime(2012, 6, 4, 0), 'Sals', 2839.60, 25], [datetime.datetime(2012, 8, 12, 0), 'PizzaHut', 2839.60, 25]]
key = 'Sals'

print( sum(i[2] for i in data if i[1] == key) )

<强>输出:

5679.2

根据评论进行编辑

import datetime
import collections
data = [[datetime.datetime(2012, 3, 1, 0), 'PizzaHut', 2839.60, 25], [datetime.datetime(2012, 12, 4, 0), 'Dominoes', 2839.60, 25], [datetime.datetime(2012, 11, 8, 0), 'Sals', 2839.60, 25], [datetime.datetime(2012, 6, 4, 0), 'Sals', 2839.60, 25], [datetime.datetime(2012, 8, 12, 0), 'PizzaHut', 2839.60, 25]]
key = 'Sals'

d = collections.defaultdict(list)
for i in data:
    d[i[1]].append(i)

print( "Sum: {0}".format(sum(i[2] for i in d[key])) )
print( "Average: {0}".format(sum(i[2] for i in d[key])/len(d[key])) )

<强>输出:

Sum: 5679.2
Average: 2839.6

按日期分组

key = datetime.datetime(2012, 12, 4, 0)

d = collections.defaultdict(list)
for i in data:
    d[i[0]].append(i)

答案 1 :(得分:1)

如果经常搜索,我会建立一个字典。

res = {}
def builddict(data):
  for ele in data:
    res.setdefault(ele[1], 0)
    res[ele[1]] += ele[2] * ele[3]

builddict(data)
print (res['Sals'])

答案 2 :(得分:1)

您可以利用namedtuple让您的代码更具可读性:

import datetime

from collections import namedtuple

dailySales = namedtuple('Data', ['day', 'store', 'income', 'transactions'])

data = [[datetime.datetime(2012, 3, 1, 0), 'PizzaHut', 2839.60, 25],
        [datetime.datetime(2012, 12, 4, 0), 'Dominoes', 2839.60, 25],
        [datetime.datetime(2012, 11, 8, 0), 'Sals', 2839.60, 25],
        [datetime.datetime(2012, 6, 4, 0), 'Sals', 2839.60, 25],
        [datetime.datetime(2012, 8, 12, 0), 'PizzaHut', 2839.60, 25]]

namedData = [dailySales(*i) for i in data]

key = 'Sals'

print(sum(j.income for j in namedData if j.store==key))
#5679.2