Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 条件和表_Python_List_Sum_Conditional Statements - Fatal编程技术网

Python 条件和表

Python 条件和表,python,list,sum,conditional-statements,Python,List,Sum,Conditional Statements,我有这样的清单: [['a', '4'], ['b', '3'], ['d', '2'], ['a', '7'], ['c', '3.5'], ['a', '4'], ['d', '4'], ['b', '5'], ['eee', '4']] a 15 b 8 c 3.5 d 6 eee 4 我想求a,b等的和,所以我想有这样的东西: [['a', '4'], ['b', '3'], ['d', '2'], ['a', '7'], ['c', '3.5'], ['a', '4'], ['d'

我有这样的清单:

[['a', '4'], ['b', '3'], ['d', '2'], ['a', '7'], ['c', '3.5'], ['a', '4'], ['d', '4'], ['b', '5'], ['eee', '4']]
a 15
b 8
c 3.5
d 6
eee 4
我想求a,b等的和,所以我想有这样的东西:

[['a', '4'], ['b', '3'], ['d', '2'], ['a', '7'], ['c', '3.5'], ['a', '4'], ['d', '4'], ['b', '5'], ['eee', '4']]
a 15
b 8
c 3.5
d 6
eee 4
另一个问题是我的数字列的类型是string,所以在求和值之前,我必须将类型更改为float。 我不能使用熊猫:

您可以使用保存一些样板代码:

from collections import defaultdict

d = defaultdict(float)

for k, v in data:
    d[k] += float(v)

for k in d:
    print(k, d[k])

a 15.0
b 8.0
d 6.0
c 3.5
eee 4.0
您可以使用itertools.groupby:

这是密码

lst = [['a', '4'], ['b', '3'], ['d', '2'], ['a', '7'], ['c', '3.5'], ['a', '4'], ['d', '4'], ['b', '5'], ['eee', '4']]
res = {}
for i in lst:
    if i[0]  in res.keys():
        res[i[0]]  += float(i[1])
        continue
    res[i[0]]  = float(i[1])
print(res.items())