以下程序完全按预期工作:
destinations = {}
while True:
query = input("Tell me where you went: ").strip()
if not query:
break
if query.count(',') != 1:
print("That's not a legal city, state combination. Please try again.\n")
continue
city, country = query.split(',')
city = city.strip()
country = country.strip()
if country not in destinations:
destinations[country] = [city]
else:
destinations[country].append(city)
temp1 = {key: sorted(destinations[key]) for key in destinations.keys()}
temp2 = {key: value for key, value in sorted(temp1.items(), key=lambda x: x[0])}
# temp2 = {}
# for key in sorted(temp1.keys()):
# temp2[key] = temp1[key]
for key, value in temp2.items():
print(key)
for elem in value:
print('\t' + elem)
样品:
Tell me where you went: Shanghai, China
Tell me where you went: Boston, USA
Tell me where you went: Beijing, China
Tell me where you went: London, England
Tell me where you went: Phoenix, USA
Tell me where you went: Hunan, China
Tell me where you went: Denver, USA
Tell me where you went: Moscow, USSR
Tell me where you went: Leningrad, USSR
Tell me where you went: San Francisco, USA
Tell me where you went: Indianapolis, USA
Tell me where you went: Jakarta, Phillipines
Tell me where you went:
China
Beijing
Hunan
Shanghai
England
London
Phillipines
Jakarta
USA
Boston
Denver
Indianapolis
Phoenix
San Francisco
USSR
Leningrad
Moscow
我不喜欢有一个方面,那就是它如何处理重复的城市,国家条目。
我正在尝试修改我的代码,以便在输入已存在的城市,国家/地区对时,输出将如下所示:
China
Beijing (2)
Shanghai
England
London
USA
Boston
Chicago (2)
New York
我认为一个好主意是将我的值列表更改为列表列表 像这样:
if country not in destinations:
destinations[country] = [[city]]
else:
destinations[country].append([city])
然后我想我会查看该城市是否已经存在以及是否存在 我会在嵌入式列表中附加一个以2开头的城市值:
destinations = {'England':[['Birmingham',2],['London'],['Wiltshire',3]]}
我无法让它发挥作用。也许有更好的方法来表示给定城市,国家/地区的多次出现?
答案 0 :(得分:0)
这是一个很好的努力。您可以使用以下代码简单地替换上一个for
循环:
<强>代码强>
import collections as ct
for country, cities in temp2.items():
counter = ct.Counter(cities)
seen = set()
print(country)
for city in cities:
count = counter[city]
if city not in seen and count > 1:
print("\t {:<20} ({})".format(city, count)) # new format
elif city not in seen:
print("\t {}".format(city)) # old format
seen.add(city)
我们在这里使用collections.Counter
来跟踪重复的城市。当我们迭代给定国家/地区的城市时,任何重复的城市都会打印在您想要的format中,否则会使用旧格式。为避免再次打印城市,每个城市都会添加到在打印前搜索的集合中。
<强>建议强>
要清理代码,请考虑通过制作两个函数来重构代码。
def get_destinations():
"""Return a dictionary of destinations from the user."""
destinations = ct.defaultdict(list)
while True:
# INSERT INPUT LOGIC HERE
destinations[country].append(city)
return destinations
def print_destinations(destinations):
"""Print city and countries."""
temp1 = {k: sorted(v) for k, v in destinations.items()}
temp2 = {k: v for k, v in sorted(temp1.items(), key=lambda x: x[0])}
# Python < 3.6, optional
# temp2 = ct.OrderedDict()
# for k, v in sorted(temp1.items()):
# temp2[k] = v
# INSERT POSTED CODE HERE
<强>演示强>
>>> dest = get_destinations()
>>> dest
Tell me where you went: Beijing, China
Tell me where you went: Atlanta, USA
Tell me where you went: Beijing, China
Tell me where you went: New York, USA
Tell me where you went:
defaultdict(list,
{'China': ['Beijing', 'Beijing'], 'USA': ['Atlanta', 'New York']})
>>> print_destinations(dest)
China
Beijing (2)
USA
Atlanta
New York
<强>详情
在get_destinations()
中,我们通过以下方式重构:
defaultdict
,将空列表设置为默认值。在print_destinations()
中,我们通过以下方式重构:
.keys()
)并对temp1
OrderedDict
(注释代码)