如何解决Python:如果其他值为真,则计算嵌套字典中值的出现次数
except:
我现在需要获取每个国家的出现次数以及回答是或否的人数。目前,我只收集每个国家的出现次数:
{
1: {'Name': {'John'},'Answer': {'yes'},'Country': {'USA'}},2: {'Name': {'Julia'},'Answer': {'no'},'Country': {'Hong Kong'}}
3: {'Name': {'Adam'},'Country': {'Hong Kong'}}
}
所以使用我的数据表我得到类似
nationalities = ['USA','Hong Kong','France' ...]
for countries in nationalities:
cnt =[item for l in [v2 for v1 in dictionary1.values() for v2 in v1.values()] for item in l].count(countries)
result.append(countries + ': ' + str(cnt))
然而,我想得到回答是和回答否的人的比例。这样我得到一个 ['Hong Kong: 2','France: 2','Italy: 3']
形式的列表,其中第一个数字是总数,第二个和第三个分别是是和否
感谢您的帮助
解决方法
以下是一个可能的解决方案,使用 defaultdict
生成结果字典,方法是为每个 yes
求和等于 no
或 country
的答案数:
from collections import defaultdict
dictionary1 = {
1: {'Name': {'John'},'Answer': {'yes'},'Country': {'USA'}},2: {'Name': {'Julia'},'Answer': {'no'},'Country': {'Hong Kong'}},3: {'Name': {'Adam'},'Country': {'Hong Kong'}}
}
nationalities = ['USA','Hong Kong','France']
result = defaultdict(list)
for countries in nationalities:
[yes,no] = [sum(list(d['Answer'])[0] == answer and list(d['Country'])[0] == countries for d in dictionary1.values()) for answer in ['yes','no']]
result[countries] = [ yes+no,yes,no ]
print(dict(result))
对于您的示例数据,这给出了
{
'USA': [1,1,0],'Hong Kong': [2,1],'France': [0,0]
}
然后您可以将其转换为字符串列表
result = [ f"{key}: {' '.join(map(str,counts))}" for key,counts in result.items()]
给出:
['USA: 1 1 0','Hong Kong: 2 1 1','France: 0 0 0']
,
a={
1: {'Name': {'John'},'Country': {'Hong Kong'}}
}
results=[]
nationalities = ['USA','France']
for country in nationalities:
countryyes=0
countryno=0
for row in a.values():
if str(row['Country'])[2:-2] == country:
if str(row['Answer'])[2:-2] == 'yes':
countryyes+=1
if str(row['Answer'])[2:-2] == 'no':
countryno+=1
results.append(country+': '+str(countryyes+countryno)+' '+str(countryyes)+' '+str(countryno))
我想做一些笔记。首先,我将国家/地区更改为国家/地区(在这样的 for 循环中使用复数名称是不正常的)。其次,我想评论并说,如果你上面的代码在一个集合中有名称、答案和国家/地区,我认为你最好将其更改为仅将其作为字符串。
,我会使用 Counter
来计算答案并使用 groupby()
按国家/地区对条目进行分组:
from collections import Counter
from operator import itemgetter
from itertools import groupby
dictionary1 = {...} # input data
group_func = itemgetter('Country')
result = []
for (country,*_),items in groupby(sorted(dictionary1.values(),key=group_func),group_func):
answers = Counter(answer.lower() for i in items for answer in i['Answer'])
result.append(f'{country} {sum(answers.values())} {answers.get("yes",0)} {answers.get("no",0)}')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。