如何在元组列表中用百分比替换数字?

时间:2015-07-27 04:18:43

标签: python tuples

我有一个包含元组的列表,需要通过应用一个简单的%公式(总和所有整数并显示替换原始整数的百分比)来更改元组中的值,其余的元组将保持不变。我不知道如何提取数字并在元组中执行此操作,只是初始代码到目前为止..

def tupleCounts2Percents(inputList):
    lst = inputList
    lst[0] = (9) #example
    print lst 

inputList = [('CA',100),('NY',300),('AZ',200)]
tupleCounts2Percents(inputList)

我需要的输出是

[('CA',0.166),('NY',0.5),('AZ',0.333)]

2 个答案:

答案 0 :(得分:3)

def tupleCounts2Percents(inputList):
    total = sum(x[1] for x in inputList)
    return [(x[0], 1.*x[1]/total) for x in inputList]

答案 1 :(得分:0)

如果要在原地更改列表,以便更改反映在调用该函数的列表中,那么您可以简单地在列表上enumerate()并创建新元组,例如 -

>>> def tupleCounts2Percents(inputList):
...     lst = inputList
...     tot = sum(x[1] for x in lst)
...     for i,x in enumerate(lst):
...         lst[i] = (x[0],(1.*x[1])/tot)
...     print lst
...
>>> inputList = [('CA',100),('NY',300),('AZ',200)]
>>> tupleCounts2Percents(inputList)
[('CA', 0.16666666666666666), ('NY', 0.5), ('AZ', 0.3333333333333333)]

这个列表理解方法 -

>>> def tupleCounts2Percents(inputList):
...     lst = inputList
...     tot = sum(x[1] for x in lst)
...     lst[:] = [(x[0],(1.*x[1])/tot) for x in lst]
...     print lst
...
>>> inputList = [('CA',100),('NY',300),('AZ',200)]
>>> tupleCounts2Percents(inputList)
[('CA', 0.16666666666666666), ('NY', 0.5), ('AZ', 0.3333333333333333)]

如果您不希望列表更改到位,则代替lst[:]使用lst,示例 -

>>> def tupleCounts2Percents(inputList):
...     lst = inputList
...     tot = sum(x[1] for x in lst)
...     lst = [(x[0],(1.*x[1])/tot) for x in lst]
...     print lst
...
>>> inputList = [('CA',100),('NY',300),('AZ',200)]
>>> tupleCounts2Percents(inputList)
[('CA', 0.16666666666666666), ('NY', 0.5), ('AZ', 0.3333333333333333)]
>>> inputList
[('CA', 100), ('NY', 300), ('AZ', 200)]