gpt4 book ai didi

python - 有没有更好的方法来打印这些键值对?

转载 作者:行者123 更新时间:2023-11-28 22:33:03 24 4
gpt4 key购买 nike

这是我在 Python 速成类(class)书中第 6 章的练习 6-9 中完成的一些代码。

favorite_places = {
'joe': {
'paris': 'france',
'hamburg': 'germany',
'cairo': 'egypt',
},
'anna': {
'tripoli': 'libya',
'tokyo': 'japan',
'moskva': 'russia',
},
'henry': {
'sydney': 'australia',
'quebec': 'canada',
'rio de janeiro': 'brazil',
}
}

for person, places in favorite_places.items():
print(person.title() + "'s favorite places are: ")
places = places.items()
for place in places:
print(place[0].title() + " in " + place[1].title() + ".")
print("\n")

那么输出是这样的:

Joe's favorite places are:
Cairo in Egypt.
Hamburg in Germany.
Paris in France.

有没有办法只从 places 变量中获取键值并像我一样打印它,但不将 places 转换为列表?我觉得这样有点乱……

最佳答案

通过这样做

places = places.items()

在 python 3 中,您没有转换为列表,而是访问一个生成键值对的迭代器,因此这是最好的实现方式。

(python 2 等价于 iteritems,在 python 2 中 items 返回一对夫妇的列表,但行为在 python 3 中发生了变化)

(最让我吃惊的是 1)你的缩进和 2)你最好直接写,而不使用数组或临时变量(直接在 2 个变量中解包这对夫妇更优雅,并使用 格式如评论中所述,更优雅和高效)

for town,country in places.items():
print("{} in {}.".format(town.title(),country.title())
print("\n")

关于python - 有没有更好的方法来打印这些键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40328907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com