简体   繁体   English

如何计算 python defaultdict 中特定键中的值的数量

[英]how to count the number of values in a specific key in a python defaultdict

I am trying to complete this question.我正在尝试完成这个问题。 I don't know where I'm going wrong..我不知道我要去哪里错了..

First line of the input is a number, which indicates how many pairs of words will follow (each pair in a separate line).输入的第一行是一个数字,表示后面有多少对单词(每对在单独的行中)。 The pairs are of the form COUNTRY CITY specifying in which country a city is located.这些对的形式为 COUNTRY CITY,指定城市所在的国家/地区。 The last line is the name of a city.最后一行是城市名称。 Print the number of cities that are located in the same country as this city.打印与该城市位于同一国家/地区的城市数量。

Hint.暗示。 Use dictionaries.使用字典。

For example, on input:例如,在输入时:

6
UK London
US Boston
UK Manchester
UK Leeds
US Dallas
Russia Moscow
Manchester

output must be: 3 output 必须是:3

from collections import defaultdict

n=input()
d=defaultdict(list)
city=' '



 for i in range(0,int(n)):
  kv=input().split()
  d[kv[0]].append(kv[1])




 for k1,v1 in d.items():
 if v1==city:
   print(len(k1))

You missing the input of the city And you need to check if the city is in the list, and just then count how many there are你错过了城市的输入你需要检查城市是否在列表中,然后计算有多少

from collections import defaultdict

n=input()
d=defaultdict(list)
city=' '



for i in range(0,int(n)):
  kv=input().split()
  d[kv[0]].append(kv[1])



city = input('Enter a city')
for k1,v1 in d.items():
 if city in v1:
   print(len(v1))

Like others mentioned, you need to take input for the query city as well.与其他人提到的一样,您也需要为查询城市输入内容。 And additionally you can approach this a bit differently - you don't need defaultdict .此外,您可以采用不同的方式处理此问题 - 您不需要defaultdict Since your query is a city, let's store that as the key in the dictionary, with the value being the country.由于您的查询是一个城市,我们将其作为键存储在字典中,值为国家。 Then we can find which country we need to get.然后我们可以找到我们需要得到哪个国家。 After than it's just a matter of counting up the values of that country in the dictionary.之后,只需在字典中计算该国家/地区的值即可。

n = input()
city_to_country = {}

for i in range(0, int(n)):
    kv = input().split()
    city_to_country[kv[1].rstrip()] = kv[0]

query_city = input()

target_country = city_to_country[query_city]

print(list(city_to_country.values()).count(target_country))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM