Fluent-python(一)数据结构

字典和集合

泛映射类型

正是因为字典至关重要,Python对它的实现做了高度优化,而散列表则是字典类型性能
出众的根本原因

什么是可散列的数据类型


如果一个对象是可散列的,那么在这个对象的生命周期中,它的散列值是不变的
而且这个对象需要实现 __hash__()方法。另外可散列对象还要有 __eq__()
方法,这样才能跟其他键做比较。如果两个可散列对象是相等的,那么它们的散列值一定是不一样的

原子不可变数据类型(str bytes 和 数值类型) 都是可散列类型, frozenset也是可散列的,
对于元祖 只有当一个元祖包含的所有元素都是可散列类型的情况下,它才是可散列的



>>> tt = (1,2,(30,40))
>>> hash(tt)
8027212646858338501
>>> tl = (1,2,[30,40])
>>> hash(tl)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> tf = (1,2,frozenset([30,40]))
>>> hash(tf)
985328935373711578
>>>

# 只有当所有内部状态都是不可变的情况下,这个对象才是可散列的



几种创建字典的方式


>>> a = dict(one=1, two=2, three=3)
>>> b = {'one':1, 'two':2, 'three':3}
>>> c = dict(zip(['one','two','three'],[1,2,3]))
>>> d = dict([('two',2), ('one',1), ('three',3)])
>>> e = dict({'three':3, 'one':1, 'two':2})
>>> a == b == c == d == e
True
>>>


字典的应用


# 为字典添加键-值对

alien = {
    'color' : 'green',
    'points' : 5,
}
print(alien['color'])
# green
print(alien['points'])
# 5

alien['x_position'] = 0
alien['y_position'] = 25
print(alien)
# {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}







# 也可以先创建一个空字典

alien1 = {}
alien1['color'] = 'yellow'
alien1['points'] = 100
print(alien1)
# {'color': 'yellow', 'points': 100}






# 修改字典中的值

alien = {
    'color' : 'green',
    'points' : 5,
}
print(alien)
# {'color': 'green', 'points': 5}
alien['color'] = 'black'
print(alien)
# {'color': 'black', 'points': 5}


alien2 = {
    'x_position' : 0,
    'y_position' : 25,
    'speed' : 'medium',
}
if alien2['speed'] == 'slow':
    x_increment = 1
elif alien2['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3
alien2['x_position'] += x_increment
print(alien2)
# {'x_position': 2, 'y_position': 25, 'speed': 'medium'}








# 删除键-值对

alien = {
    'color' : 'green',
    'points' : 5,
}
del alien['points']
print(alien)
# {'color': 'green'}
# del删除的键值对永远消失

开放式字典

favorite_languages = {
    'jen' : 'python',
    'sarah' : 'C',
    'edward' : 'ruby',
    'phil' : 'python',
}
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + '.')
# Sarah's favorite language is C.











# 遍历字典
user = {
    'username' : 'krischung',
    'first' : 'kris',
    'last' : 'chung',
}
for key,value in user.items():
    print(key + ' : ' + value)
'''
    username : krischung
    first : kris
    last : chung
    items()的效果
'''

## 遍历字典中所有的键
favorite_languages = {
    'jen' : 'python',
    'sarah' : 'C',
    'edward' : 'ruby',
    'phil' : 'python',
}
for name in favorite_languages.keys():
    print(name.title())

'''
    keys() 方法的应用
    Jen
    Sarah
    Edward
    Phil
'''

for value in favorite_languages.values():
    print(value)
'''
    values() 方法的应用
    python
    C
    ruby
    python

'''

favorite_languages = {
    'jen' : 'python',
    'sarah' : 'C',
    'edward' : 'ruby',
    'phil' : 'python',
}

friends = ['phil', 'sarah']
for name in favorite_languages.keys():
    print(name.title())

    if name in friends:
        print(' Hi ' + name.title() +
              ", I see your favorite language is " +
              favorite_languages[name].title() + '!')

'''
    Jen
    Sarah
     Hi Sarah, I see your favorite language is C!
    Edward
    Phil
     Hi Phil, I see your favorite language is Python!

'''


favorite_languages = {
    'jen' : 'python',
    'sarah' : 'C',
    'edward' : 'ruby',
    'phil' : 'python',
}
if 'erin' not in favorite_languages.keys():
    print('Erin, please take our poll!')
# Erin, please take our poll!

for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.")

'''
    sorted()正序排序,字符串则按字母前后排序
    Edward, thank you for taking the poll.
    Jen, thank you for taking the poll.
    Phil, thank you for taking the poll.
    Sarah, thank you for taking the poll.
'''



#遍历字典中的所有值


favorite_languages = {
    'jen' : 'python',
    'sarah' : 'C',
    'edward' : 'ruby',
    'phil' : 'python',
}
print('The following languages have been mentioned:')
for language in favorite_languages.values():
    print(language.title())

'''
    The following languages have been mentioned:
    Python
    C
    Ruby
    Python
'''

for language in set(favorite_languages.values()):
    print(language.title())
'''
    set()构造一个集合,且集合内的每个元素都必须是独一无二的
    Ruby
    Python
    C
'''













# 嵌套

alien1 = {'color' : 'green', 'points' : 5}
alien2 = {'color' : 'red', 'points' : 10}
alien3 = {'color' : 'yellow', 'points' : 15}

aliens = [alien1, alien2, alien3]
print(aliens)
# [{'color': 'green', 'points': 5}, {'color': 'red', 'points': 10}, {'color': 'yellow', 'points': 15}]

for alien in aliens:
    print(alien)
'''
    {'color': 'green', 'points': 5}
    {'color': 'red', 'points': 10}
    {'color': 'yellow', 'points': 15}
'''







# eg1

创建一个空列表
aliens = []

# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color' : 'green', 'points' : 5, 'speed' : 'slow'}
    aliens.append(new_alien)

# 显示前五个外星人
for alien in aliens[:5]:
    print(alien)
print('...')

# 显示创建了多少个外星人
print('Total number of aliens: ' + str(len(aliens)))





列表嵌套于字典
favorite_languages = {
    'jen' : ['python', 'ruby'],
    'sarah' : ['c'],
    'edward' : ['ruby', 'go'],
    'phil' : ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
    print('\n' + name.title() + " 's favorite languages are: ")
    for language in languages:
        print('\t' + language.title())

'''
    列表嵌套于字典的遍历
    Jen 's favorite languages are:
        Python
        Ruby

    Sarah 's favorite languages are:
        C

    Edward 's favorite languages are:
        Ruby
        Go

    Phil 's favorite languages are:
        Python
        Haskell
'''






# 字典嵌套于字典

users = {
    'aeinstein' : {
        'first' : 'albert',
        'last' : 'einstein',
        'location' : 'princeton',
    },

    'mcurie' : {
        'first' : 'marie',
        'last' : 'curie',
        'location' : 'paris',
    },
}

for username, user_info in users.items():
    print('\nUsername: ' + username )
    full_name = user_info['first'] + ' ' + user_info['last']
    location = user_info['location']

    print('\tFull name: ' + full_name.title())
    print('\t Location: ' + location.title())

'''

    Username: aeinstein
        Full name: Albert Einstein
        Location: Princeton

    Username: mcurie
        Full name: Marie Curie
        Location: Paris

'''






字典推导式

# 一个嵌套元祖的列表
>>> DIAL_CODES = [
...     (86, 'China'),
...     (91, 'India'),
...     (1, 'United States'),
...     (62, 'Indonesia'),
...     (55, 'Brazil'),
...     (92, 'Pakistan'),
...     (880, 'Bangladesh'),
...     (234, 'Nigeria'),
...     (7, 'Russia'),
...     (81, 'Japan'),
... ]
>>>
# 字典推导式
>>> country_code = {country : code for code,country in DIAL_CODES}
>>> country_code
{'China': 86, 'India': 91, 'United States': 1, 'Indonesia': 62, 'Brazil': 55, 'Pakistan': 92, 'Bangladesh': 880, 'Nigeria': 234, 'Russia': 7, 'Japan':
 81}
>>>
>>> {code : country.upper() for country,code in country_code.items() if code < 66}
{1: 'UNITED STATES', 62: 'INDONESIA', 55: 'BRAZIL', 7: 'RUSSIA'}
>>>
>>>
# 修改字典内的值可以修改
>>> country_code['China'] = 100
>>> country_code
{'China': 100, 'India': 91, 'United States': 1, 'Indonesia': 62, 'Brazil': 55, 'Pakistan': 92, 'Bangladesh': 880, 'Nigeria': 234, 'Russia': 7, 'Japan'
: 81}
>>>


# 推导式的条件

>>> code
[['china', 86], ['php', 100], ['python', 56]]
>>> code.append(['CCC',200,15])
>>> code
[['china', 86], ['php', 100], ['python', 56], ['CCC', 200, 15]]
>>> dicts = {key : value for value,key in code}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
ValueError: too many values to unpack (expected 2)
>>>

'''
    字典推导式是将相应的列表等结构转化为字典,
    然而列表等结构中的元素必须符合推导式的格式
'''


猜你喜欢

转载自blog.csdn.net/qq_39469688/article/details/82220706
今日推荐