Python:不同类型的字典键数据

时间:2019-06-18 01:04:38

标签: python

给出如下字典:

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}

如何分别计算int键和字符串键的平均值?

4 个答案:

答案 0 :(得分:2)

您需要检查key是否为int并计算均值:

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}


total_int = 0
count_str = 0
total_str = 0
count_int = 0
for keys,values in dic.items():

if type(keys) is int :
    count_int = count_int + 1
    total_int = total_int + values
    print (values)

elif type(keys) is str :
    count_str = count_str + 1
    total_str = total_str + values


print (total_int/count_int)
print (total_str/count_str)

答案 1 :(得分:2)

我认为(?)OP需要整数键项的值的均值以及字符串键项的单独的均值。这是一个替代选项:

 dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}

 int_keyed_values = [v for k,v in dic.items() if type(k) is int]
 str_keyed_values = [v for k,v in dic.items() if type(k) is str]

 int_mean = sum(int_keyed_values)/len(int_keyed_values)
 str_mean = sum(str_keyed_values)/len(str_keyed_values)

答案 2 :(得分:2)

字符串键的值是什么意思?如果它们是单字符键,则假定您要计算键的ASCI值。如果是这种情况,这里是执行此操作的代码

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30
total_int = 0
total_str = 0
count_int = 0
count_str = 0
for keys,values in dic.items():
    if type(keys) is int : #checking the key is int 
        count_int +=  1
        total_int += keys
     elif type(keys) is str: 
        count_str +=  1
        total_str += ord(keys)

print total_int/count_int # will print int avg
print total_str/count_str # will print str avg

答案 3 :(得分:2)

想介绍一种不太常见的方法:

package com.example1.demo.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.example1.demo.model.Interview;
import com.example1.demo.model.ASimpleUserInterview;



@Repository
public interface InterviewRepository extends JpaRepository<Interview, Long> {

    @Query("select new com.example1.demo.model.ASimpleUserInterview(a,i) from User as a inner join Interview as i on a.id=i.supervisorId inner join MarketingSub as m on i.submissionId=m.id where m.consultantId=91")
    public List<ASimpleUserInterview> findByInterviews();
}

from operator import itemgetter
from statistics import mean
from itertools import groupby

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}
[mean(itemgetter(*g)(dic)) for _, g in groupby(dic, key=lambda k: isinstance(k, int))]
# [20, 20]

可能的开销,但是非常合适。而且,这三个助手很有趣:-)