如何从重复元素中添加值

用户名

这是我在python中的代码:

from array import *
date =      array('I',  [11,  11,    12,    11,     2,      7,      2])
saleAmount = array('I', [500, 25000, 51000, 100000, 125999, 126000, 202000])

for x in range(0,7):
    if date[x] == 1:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 2:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 3:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 4:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 5:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 6:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 7:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 8:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 9:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 10:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 11:
    totalsale = saleAmount[x]
    print(date[x], totalsale)
if date[x] == 12:
    totalsale = saleAmount[x]
    print(date[x], totalsale)

我在数据中发现了重复项。现在,我想添加重复项(例如,如果11次出现多次,则添加所有11次的对应值)

输出将是这样的:

11, 12550

我该怎么做?

WNG

您的问题不是很清楚,但是您要尽力而为,这应该给您几点。

首先,关于您的代码的几点评论:

  • 您似乎有12种不同的情况会导致相同的结果。我不知道您到底想做什么,但是很明显,您可以减少代码。例如,您可以用单个替换您的12个条件

    如果date [x]在范围(1,13)中

  • 看来您的代码没有正确缩进,您需要缩进for循环中的所有行,并为受if条件约束的代码行添加额外的缩进。这就是python的编写方式,缩进非常重要。

要回答您的问题,我相信对所有具有相同日期的销售额求和的最简单方法是使用字典结构。它可以使销售值按日期建立索引,并且不会有空值:

#we declare a dictionary
SalesByDate={}
#we fill the dictionary using a for loop
for x in range(0,7):
#if the entry for the date is not in the dictionary, you create it
    if date[x] not in SalesByDate:
        SalesByDate[date[x]]=0
#you then add the value of the sale to the corresponding date
    SalesByDate[date[x]]+=saleAmount[x]

然后,您便有了字典。您可以直接打印:

print(SalesByDate)

但这不是很好看。要打印它的每一行:

for entry in sorted(SalesByDate.keys()):
    print(entry,SalesByDate[entry])

要访问日期11的总销售额,您需要使用以下语法

SalesByDate[11]

这将与您的数据产生结果

125500

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章