[英]How to replace numbers by their percentages in a list of tuples?
I have a list with tuples and need to change values in the tuples by apply a simple % formula (sum all the integers and display the percentage in replacement of the original integer) the rest of the tuple is to remain the same. 我有一个包含元组的列表,需要通过应用简单的%公式更改所有元组中的值(求和所有整数并显示替换原始整数的百分比),其余的元组将保持不变。 I am not sure how to extract the number and perform this in the tuple, just initial code so far..
我不确定如何提取数字并在元组中执行此操作,到目前为止,还只是初始代码。
def tupleCounts2Percents(inputList):
lst = inputList
lst[0] = (9) #example
print lst
inputList = [('CA',100),('NY',300),('AZ',200)]
tupleCounts2Percents(inputList)
the output I need is 我需要的输出是
[('CA',0.166),('NY',0.5),('AZ',0.333)]
def tupleCounts2Percents(inputList):
total = sum(x[1] for x in inputList)
return [(x[0], 1.*x[1]/total) for x in inputList]
If you want to change the list in-place, such that the change reflects in the list using which the function was called, then you can simply enumerate()
over the list and create new tuples, example - 如果您想就地更改列表,以使更改反映在调用函数所使用的列表中,那么您可以简单地在列表上
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)]
A list comprehension method for this - 列表理解方法-
>>> 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)]
If you do not want the list to change inplace, then instead of lst[:]
use lst
, Example - 如果您不希望列表在原位置更改,请使用
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.