循环通过元组并计算数字的百分比

时间:2016-12-08 09:56:01

标签: python python-2.7 list tuples

我正在尝试遍历以下tupletuple1),从整数(b)创建总计,计算百分比每个值代表并将其与变量a一起存储在新变量(a_percent

我尝试过以下方法:

tuple1 = [('Data1', 33), ('Data2', 52), ('Data3', 85)]

total = b
for a, b in tuple1:
    total += b
    y = b/total*100.0
    a_percent = a, y

a_percent的 预期 输出是例如对于Data1 :( 33/(33+52+85)*100):

Data1, 19.4 ...   
Data2, 30.5 ...
Data3, 50

然而,如下所示:

('Data1', 100.0)
('Data2', 0.0)
('Data3', 0.0)

6 个答案:

答案 0 :(得分:2)

在您尝试的基本解决方案中。可以帮助您轻松理解这一点。

tuple1 = [('Data1', 33), ('Data2', 52), ('Data3', 85)]

total = 0
for a, b in tuple1:
    total += int(b)

for a,b in tuple1:
    y = float(int(b)) * 100 /total
    a_percent = a, y
    print a_percent

输出:

('Data1', 19.41176470588235)
('Data2', 30.58823529411765)
('Data3', 50.0)

答案 1 :(得分:1)

当两者都是整数时,你会b/y,导致整数除法。之后乘以100.0并不重要。可以float(b)/y*100.0b*100.0/y

虽然这段代码没有按照您的意愿行事,但您无法获得每个值没有两个循环的百分比。相反,我可以建议

total = sum([t[1] for t in tuple1])
a_percent = [(t[0], float(t[1])/total) for t in tuple1]

答案 2 :(得分:1)

您可以先取total,然后循环计算百分比:

>>> tuple1 = [('Data1', 33), ('Data2', 52), ('Data3', 85)]
>>> total = sum(t[1] for t in tuple1)
>>> tuple_new = [(x, float(y) * 100 /total) for x, y in tuple1]
>>> tuple_new
[('Data1', 19.41176470588235), ('Data2', 30.58823529411765), ('Data3', 50.0)]

如果需要,您也可以在元组中包含实际计数:

>>> [(x, y, float(y) * 100 /total) for x, y in tuple1]
[('Data1', 33, 19.41176470588235), ('Data2', 52, 30.58823529411765), ('Data3', 85, 50.0)]

答案 3 :(得分:0)

[y[1] for y in tuple1]
sum_tuple = sum([y[1] for y in tuple1])
[(y[0], (float(y[1])/sum_tuple)*100) for y in tuple1]

输出:

[('Data1', 19.411764705882355), ('Data2', 30.58823529411765), ('Data3', 50.0)]

答案 4 :(得分:0)

一个简单的答案(尚未测试)

total = 0
for data, value in tuple1:
      total += value     #get the total

for data,value in tuple1:
      print float(value) / total * 100

答案 5 :(得分:0)

另一个简单的应用:

tuple1 = [('Data1', 33), ('Data2', 52), ('Data3', 85)]

total = (sum(t[1] for t in tuple1))
for a, b in tuple1:
    y = b * 100 / total
    a_percent = a, y
    print(a_percent)

输出:

('Data1', 19.41176470588235)
('Data2', 30.58823529411765)
('Data3', 50.0)