簡體   English   中英

Python字典列印選項

[英]Python Dictionaries Print Options

代碼來自Learn Python The Hard Way練習39。請在第一組代碼下面查看我的問題。

# create a mapping of state to abbreviation
states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI'
}

# create a basic set of states and some cities in them
cities = {
    'CA': 'San Francisco',
    'MI': 'Detroit',
    'FL': 'Jacksonville'
}

# do it by using the state then cities dict
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]

當您可以像下面這樣簡單地打印時,為什么要用上面的方法打印出來?

print '-' * 10
print "Michigan has: ", cities['MI']
print "Florida has: ", cities['FL']

我想知道我是否在這里錯過了一些重要的事情。 它僅用於學習目的嗎? 如果是這樣,那我到底在學什么? 請澄清。

首先是更一般的:

>>> for state in ('Michigan', 'Florida'):
...    print '%s has: %s' % (state, cities[states[state]])
... 

第二種方法不能以這種方式概括,因為突然之間您需要先驗知道狀態碼。

只要知道該州的名稱及其縮寫,您就可以以任何一種方式進行操作。 但是書中介紹的方法很容易以有用的方式進行修改,例如

for state, abbreviation in states.items():
    if abbreviation in cities:
        print state, "has: ", cities[abbreviation]

獲取州/市對的列表。

看看漂亮的打印標准庫:

http://docs.python.org/2/library/pprint.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM