Python基础知识速查(下)


9. Dictionaries

  • Dictionary properties: unordered, iterable, mutable, can contain multiple data types
  • Made of key-value pairs
  • Keys must be unique, and can be strings, numbers, or tuples
  • Values can be any type
In [125]:
# create an empty dictionary (two ways)
empty_dict = {}
empty_dict = dict()
In [126]:
# create a dictionary (two ways)
family = {'dad':'homer', 'mom':'marge', 'size':6}
family = dict(dad='homer', mom='marge', size=6)
family
Out[126]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}
In [127]:
# convert a list of tuples into a dictionary
list_of_tuples = [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]
family = dict(list_of_tuples)
family
Out[127]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}

Examine a dictionary:

In [128]:
# pass a key to return its value
family['dad']
Out[128]:
'homer'
In [129]:
# return the number of key-value pairs
len(family)
Out[129]:
3
In [130]:
# check if key exists in dictionary
'mom' in family
Out[130]:
True
In [131]:
# dictionary values are not checked
'marge' in family
Out[131]:
False
In [132]:
# returns a list of keys (Python 2) or an iterable view (Python 3)
family.keys()
Out[132]:
['dad', 'mom', 'size']
In [133]:
# returns a list of values (Python 2) or an iterable view (Python 3)
family.values()
Out[133]:
['homer', 'marge', 6]
In [134]:
# returns a list of key-value pairs (Python 2) or an iterable view (Python 3)
family.items()
Out[134]:
[('dad', 'homer'), ('mom', 'marge'), ('size', 6)]

Modify a dictionary (does not return the dictionary):

In [135]:
# add a new entry
family['cat'] = 'snowball'
family
Out[135]:
{'cat': 'snowball', 'dad': 'homer', 'mom': 'marge', 'size': 6}
In [136]:
# edit an existing entry
family['cat'] = 'snowball ii'
family
Out[136]:
{'cat': 'snowball ii', 'dad': 'homer', 'mom': 'marge', 'size': 6}
In [137]:
# delete an entry
del family['cat']
family
Out[137]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}
In [138]:
# dictionary value can be a list
family['kids'] = ['bart', 'lisa']
family
Out[138]:
{'dad': 'homer', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}
In [139]:
# remove an entry and return the value
family.pop('dad')
Out[139]:
'homer'
In [140]:
# add multiple entries
family.update({'baby':'maggie', 'grandpa':'abe'})
family
Out[140]:
{'baby': 'maggie',
 'grandpa': 'abe',
 'kids': ['bart', 'lisa'],
 'mom': 'marge',
 'size': 6}

Access values more safely with get:

In [141]:
family['mom']
Out[141]:
'marge'
In [142]:
# equivalent to a dictionary lookup
family.get('mom')
Out[142]:
'marge'
In [143]:
# this would throw an error since the key does not exist
# family['grandma']
In [144]:
# return None if not found
family.get('grandma')
In [145]:
# provide a default return value if not found
family.get('grandma', 'not found')
Out[145]:
'not found'

Access a list element within a dictionary:

In [146]:
family['kids'][0]
Out[146]:
'bart'
In [147]:
family['kids'].remove('lisa')
family
Out[147]:
{'baby': 'maggie',
 'grandpa': 'abe',
 'kids': ['bart'],
 'mom': 'marge',
 'size': 6}

String substitution using a dictionary:

In [148]:
'youngest child is %(baby)s' % family
Out[148]:
'youngest child is maggie'

10. Sets

  • Set properties: unordered, iterable, mutable, can contain multiple data types
  • Made of unique elements (strings, numbers, or tuples)
  • Like dictionaries, but with keys only (no values)
In [149]:
# create an empty set
empty_set = set()
In [150]:
# create a set directly
languages = {'python', 'r', 'java'}
In [151]:
# create a set from a list
snakes = set(['cobra', 'viper', 'python'])

Examine a set:

In [152]:
len(languages)
Out[152]:
3
In [153]:
'python' in languages
Out[153]:
True

Set operations:

In [154]:
# intersection
languages & snakes
Out[154]:
{'python'}
In [155]:
# union
languages | snakes
Out[155]:
{'cobra', 'java', 'python', 'r', 'viper'}
In [156]:
# set difference
languages - snakes
Out[156]:
{'java', 'r'}
In [157]:
# set difference
snakes - languages
Out[157]:
{'cobra', 'viper'}

Modify a set (does not return the set):

In [158]:
# add a new element
languages.add('sql')
languages
Out[158]:
{'java', 'python', 'r', 'sql'}
In [159]:
# try to add an existing element (ignored, no error)
languages.add('r')
languages
Out[159]:
{'java', 'python', 'r', 'sql'}
In [160]:
# remove an element
languages.remove('java')
languages
Out[160]:
{'python', 'r', 'sql'}
In [161]:
# try to remove a non-existing element (this would throw an error)
# languages.remove('c')
In [162]:
# remove an element if present, but ignored otherwise
languages.discard('c')
languages
Out[162]:
{'python', 'r', 'sql'}
In [163]:
# remove and return an arbitrary element
languages.pop()
Out[163]:
'python'
In [164]:
# remove all elements
languages.clear()
languages
Out[164]:
set()
In [165]:
# add multiple elements (can also pass a set)
languages.update(['go', 'spark'])
languages
Out[165]:
{'go', 'spark'}

Get a sorted list of unique elements from a list:

In [166]:
sorted(set([9, 0, 2, 1, 0]))
Out[166]:
[0, 1, 2, 9]

11. Defining Functions

Define a function with no arguments and no return values:

In [167]:
def print_text():
    print('this is text')
In [168]:
# call the function
print_text()
this is text

Define a function with one argument and no return values:

In [169]:
def print_this(x):
    print(x)
In [170]:
# call the function
print_this(3)
3
In [171]:
# prints 3, but doesn't assign 3 to n because the function has no return statement
n = print_this(3)
3

Define a function with one argument and one return value:

In [172]:
def square_this(x):
    return x**2
In [173]:
# include an optional docstring to describe the effect of a function
def square_this(x):
    """Return the square of a number."""
    return x**2
In [174]:
# call the function
square_this(3)
Out[174]:
9
In [175]:
# assigns 9 to var, but does not print 9
var = square_this(3)

Define a function with two 'positional arguments' (no default values) and one 'keyword argument' (has a default value):

In [176]:
def calc(a, b, op='add'):
    if op == 'add':
        return a + b
    elif op == 'sub':
        return a - b
    else:
        print('valid operations are add and sub')
In [177]:
# call the function
calc(10, 4, op='add')
Out[177]:
14
In [178]:
# unnamed arguments are inferred by position
calc(10, 4, 'add')
Out[178]:
14
In [179]:
# default for 'op' is 'add'
calc(10, 4)
Out[179]:
14
In [180]:
calc(10, 4, 'sub')
Out[180]:
6
In [181]:
calc(10, 4, 'div')
valid operations are add and sub

Use pass as a placeholder if you haven't written the function body:

In [182]:
def stub():
    pass

Return two values from a single function:

In [183]:
def min_max(nums):
    return min(nums), max(nums)
In [184]:
# return values can be assigned to a single variable as a tuple
nums = [1, 2, 3]
min_max_num = min_max(nums)
min_max_num
Out[184]:
(1, 3)
In [185]:
# return values can be assigned into multiple variables using tuple unpacking
min_num, max_num = min_max(nums)
print(min_num)
print(max_num)
1
3

12. Anonymous (Lambda) Functions

  • Primarily used to temporarily define a function for use by another function
In [186]:
# define a function the "usual" way
def squared(x):
    return x**2
In [187]:
# define an identical function using lambda
squared = lambda x: x**2

Sort a list of strings by the last letter:

In [188]:
# without using lambda
simpsons = ['homer', 'marge', 'bart']
def last_letter(word):
    return word[-1]
sorted(simpsons, key=last_letter)
Out[188]:
['marge', 'homer', 'bart']
In [189]:
# using lambda
sorted(simpsons, key=lambda word: word[-1])
Out[189]:
['marge', 'homer', 'bart']

13. For Loops and While Loops

range returns a list of integers (Python 2) or a sequence (Python 3):

In [190]:
# includes the start value but excludes the stop value
range(0, 3)
Out[190]:
[0, 1, 2]
In [191]:
# default start value is 0
range(3)
Out[191]:
[0, 1, 2]
In [192]:
# third argument is the step value
range(0, 5, 2)
Out[192]:
[0, 2, 4]
In [193]:
# Python 2 only: use xrange to create a sequence rather than a list (saves memory)
xrange(100, 100000, 5)
Out[193]:
xrange(100, 100000, 5)

for loops:

In [194]:
# not the recommended style
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
    print(fruits[i].upper())
APPLE
BANANA
CHERRY
In [195]:
# recommended style
for fruit in fruits:
    print(fruit.upper())
APPLE
BANANA
CHERRY
In [196]:
# iterate through two things at once (using tuple unpacking)
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
    print(key, value)
('dad', 'homer')
('mom', 'marge')
('size', 6)
In [197]:
# use enumerate if you need to access the index value within the loop
for index, fruit in enumerate(fruits):
    print(index, fruit)
(0, 'apple')
(1, 'banana')
(2, 'cherry')

for/else loop:

In [198]:
for fruit in fruits:
    if fruit == 'banana':
        print('Found the banana!')
        break    # exit the loop and skip the 'else' block
else:
    # this block executes ONLY if the for loop completes without hitting 'break'
    print("Can't find the banana")
Found the banana!

while loop:

In [199]:
count = 0
while count < 5:
    print('This will print 5 times')
    count += 1    # equivalent to 'count = count + 1'
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times

14. Comprehensions

List comprehension:

In [200]:
# for loop to create a list of cubes
nums = [1, 2, 3, 4, 5]
cubes = []
for num in nums:
    cubes.append(num**3)
cubes
Out[200]:
[1, 8, 27, 64, 125]
In [201]:
# equivalent list comprehension
cubes = [num**3 for num in nums]
cubes
Out[201]:
[1, 8, 27, 64, 125]
In [202]:
# for loop to create a list of cubes of even numbers
cubes_of_even = []
for num in nums:
    if num % 2 == 0:
        cubes_of_even.append(num**3)
cubes_of_even
Out[202]:
[8, 64]
In [203]:
# equivalent list comprehension
# syntax: [expression for variable in iterable if condition]
cubes_of_even = [num**3 for num in nums if num % 2 == 0]
cubes_of_even
Out[203]:
[8, 64]
In [204]:
# for loop to cube even numbers and square odd numbers
cubes_and_squares = []
for num in nums:
    if num % 2 == 0:
        cubes_and_squares.append(num**3)
    else:
        cubes_and_squares.append(num**2)
cubes_and_squares
Out[204]:
[1, 8, 9, 64, 25]
In [205]:
# equivalent list comprehension (using a ternary expression)
# syntax: [true_condition if condition else false_condition for variable in iterable]
cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums]
cubes_and_squares
Out[205]:
[1, 8, 9, 64, 25]
In [206]:
# for loop to flatten a 2d-matrix
matrix = [[1, 2], [3, 4]]
items = []
for row in matrix:
    for item in row:
        items.append(item)
items
Out[206]:
[1, 2, 3, 4]
In [207]:
# equivalent list comprehension
items = [item for row in matrix
              for item in row]
items
Out[207]:
[1, 2, 3, 4]

Set comprehension:

In [208]:
fruits = ['apple', 'banana', 'cherry']
unique_lengths = {len(fruit) for fruit in fruits}
unique_lengths
Out[208]:
{5, 6}

Dictionary comprehension:

In [209]:
fruit_lengths = {fruit:len(fruit) for fruit in fruits}
fruit_lengths
Out[209]:
{'apple': 5, 'banana': 6, 'cherry': 6}
In [210]:
fruit_indices = {fruit:index for index, fruit in enumerate(fruits)}
fruit_indices
Out[210]:
{'apple': 0, 'banana': 1, 'cherry': 2}

15. Map and Filter

map applies a function to every element of a sequence and returns a list (Python 2) or iterator (Python 3):

In [211]:
simpsons = ['homer', 'marge', 'bart']
map(len, simpsons)
Out[211]:
[5, 5, 4]
In [212]:
# equivalent list comprehension
[len(word) for word in simpsons]
Out[212]:
[5, 5, 4]
In [213]:
map(lambda word: word[-1], simpsons)
Out[213]:
['r', 'e', 't']
In [214]:
# equivalent list comprehension
[word[-1] for word in simpsons]
Out[214]:
['r', 'e', 't']

filter returns a list (Python 2) or iterator (Python 3) containing the elements from a sequence for which a condition is True:

In [215]:
nums = range(5)
filter(lambda x: x % 2 == 0, nums)
Out[215]:
[0, 2, 4]
In [216]:
# equivalent list comprehension
[num for num in nums if num % 2 == 0]
Out[216]:
[0, 2, 4]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值