Python基础知识速查(下)

来源:互联网 发布:济宁网络问政平台app 编辑:程序博客网 时间:2024/06/05 17:53


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 dictionarylist_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 valuefamily['dad']
Out[128]:
'homer'
In [129]:
# return the number of key-value pairslen(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 entryfamily['cat'] = 'snowball'family
Out[135]:
{'cat': 'snowball', 'dad': 'homer', 'mom': 'marge', 'size': 6}
In [136]:
# edit an existing entryfamily['cat'] = 'snowball ii'family
Out[136]:
{'cat': 'snowball ii', 'dad': 'homer', 'mom': 'marge', 'size': 6}
In [137]:
# delete an entrydel family['cat']family
Out[137]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}
In [138]:
# dictionary value can be a listfamily['kids'] = ['bart', 'lisa']family
Out[138]:
{'dad': 'homer', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}
In [139]:
# remove an entry and return the valuefamily.pop('dad')
Out[139]:
'homer'
In [140]:
# add multiple entriesfamily.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 lookupfamily.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 foundfamily.get('grandma')
In [145]:
# provide a default return value if not foundfamily.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'

[Back to top]

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 setempty_set = set()
In [150]:
# create a set directlylanguages = {'python', 'r', 'java'}
In [151]:
# create a set from a listsnakes = 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]:
# intersectionlanguages & snakes
Out[154]:
{'python'}
In [155]:
# unionlanguages | snakes
Out[155]:
{'cobra', 'java', 'python', 'r', 'viper'}
In [156]:
# set differencelanguages - snakes
Out[156]:
{'java', 'r'}
In [157]:
# set differencesnakes - languages
Out[157]:
{'cobra', 'viper'}

Modify a set (does not return the set):

In [158]:
# add a new elementlanguages.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 elementlanguages.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 otherwiselanguages.discard('c')languages
Out[162]:
{'python', 'r', 'sql'}
In [163]:
# remove and return an arbitrary elementlanguages.pop()
Out[163]:
'python'
In [164]:
# remove all elementslanguages.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]

[Back to top]

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 functionprint_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 functionprint_this(3)
3
In [171]:
# prints 3, but doesn't assign 3 to n because the function has no return statementn = 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 functiondef square_this(x):    """Return the square of a number."""    return x**2
In [174]:
# call the functionsquare_this(3)
Out[174]:
9
In [175]:
# assigns 9 to var, but does not print 9var = 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 functioncalc(10, 4, op='add')
Out[177]:
14
In [178]:
# unnamed arguments are inferred by positioncalc(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 tuplenums = [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 unpackingmin_num, max_num = min_max(nums)print(min_num)print(max_num)
13

[Back to top]

12. Anonymous (Lambda) Functions

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

Sort a list of strings by the last letter:

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

[Back to top]

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 valuerange(0, 3)
Out[190]:
[0, 1, 2]
In [191]:
# default start value is 0range(3)
Out[191]:
[0, 1, 2]
In [192]:
# third argument is the step valuerange(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 stylefruits = ['apple', 'banana', 'cherry']for i in range(len(fruits)):    print(fruits[i].upper())
APPLEBANANACHERRY
In [195]:
# recommended stylefor fruit in fruits:    print(fruit.upper())
APPLEBANANACHERRY
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 loopfor 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' blockelse:    # 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 = 0while count < 5:    print('This will print 5 times')    count += 1    # equivalent to 'count = count + 1'
This will print 5 timesThis will print 5 timesThis will print 5 timesThis will print 5 timesThis will print 5 times

[Back to top]

14. Comprehensions

List comprehension:

In [200]:
# for loop to create a list of cubesnums = [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 comprehensioncubes = [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 numberscubes_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 numberscubes_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-matrixmatrix = [[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 comprehensionitems = [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}

[Back to top]

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]

[Back to top]


1 0
原创粉丝点击