Python基础知识速查(下)
来源:互联网 发布:济宁网络问政平台app 编辑:程序博客网 时间:2024/06/05 17:53
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]:
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]:
In [128]:
# pass a key to return its valuefamily['dad']
Out[128]:
In [129]:
# return the number of key-value pairslen(family)
Out[129]:
In [130]:
# check if key exists in dictionary'mom' in family
Out[130]:
In [131]:
# dictionary values are not checked'marge' in family
Out[131]:
In [132]:
# returns a list of keys (Python 2) or an iterable view (Python 3)family.keys()
Out[132]:
In [133]:
# returns a list of values (Python 2) or an iterable view (Python 3)family.values()
Out[133]:
In [134]:
# returns a list of key-value pairs (Python 2) or an iterable view (Python 3)family.items()
Out[134]:
In [135]:
# add a new entryfamily['cat'] = 'snowball'family
Out[135]:
In [136]:
# edit an existing entryfamily['cat'] = 'snowball ii'family
Out[136]:
In [137]:
# delete an entrydel family['cat']family
Out[137]:
In [138]:
# dictionary value can be a listfamily['kids'] = ['bart', 'lisa']family
Out[138]:
In [139]:
# remove an entry and return the valuefamily.pop('dad')
Out[139]:
In [140]:
# add multiple entriesfamily.update({'baby':'maggie', 'grandpa':'abe'})family
Out[140]:
In [141]:
family['mom']
Out[141]:
In [142]:
# equivalent to a dictionary lookupfamily.get('mom')
Out[142]:
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]:
In [146]:
family['kids'][0]
Out[146]:
In [147]:
family['kids'].remove('lisa')family
Out[147]:
In [148]:
'youngest child is %(baby)s' % family
Out[148]:
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'])
In [152]:
len(languages)
Out[152]:
In [153]:
'python' in languages
Out[153]:
In [154]:
# intersectionlanguages & snakes
Out[154]:
In [155]:
# unionlanguages | snakes
Out[155]:
In [156]:
# set differencelanguages - snakes
Out[156]:
In [157]:
# set differencesnakes - languages
Out[157]:
In [158]:
# add a new elementlanguages.add('sql')languages
Out[158]:
In [159]:
# try to add an existing element (ignored, no error)languages.add('r')languages
Out[159]:
In [160]:
# remove an elementlanguages.remove('java')languages
Out[160]:
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]:
In [163]:
# remove and return an arbitrary elementlanguages.pop()
Out[163]:
In [164]:
# remove all elementslanguages.clear()languages
Out[164]:
In [165]:
# add multiple elements (can also pass a set)languages.update(['go', 'spark'])languages
Out[165]:
In [166]:
sorted(set([9, 0, 2, 1, 0]))
Out[166]:
In [167]:
def print_text(): print('this is text')
In [168]:
# call the functionprint_text()
In [169]:
def print_this(x): print(x)
In [170]:
# call the functionprint_this(3)
In [171]:
# prints 3, but doesn't assign 3 to n because the function has no return statementn = print_this(3)
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]:
In [175]:
# assigns 9 to var, but does not print 9var = square_this(3)
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]:
In [178]:
# unnamed arguments are inferred by positioncalc(10, 4, 'add')
Out[178]:
In [179]:
# default for 'op' is 'add'calc(10, 4)
Out[179]:
In [180]:
calc(10, 4, 'sub')
Out[180]:
In [181]:
calc(10, 4, 'div')
In [182]:
def stub(): pass
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]:
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)
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
In [188]:
# without using lambdasimpsons = ['homer', 'marge', 'bart']def last_letter(word): return word[-1]sorted(simpsons, key=last_letter)
Out[188]:
In [189]:
# using lambdasorted(simpsons, key=lambda word: word[-1])
Out[189]:
In [190]:
# includes the start value but excludes the stop valuerange(0, 3)
Out[190]:
In [191]:
# default start value is 0range(3)
Out[191]:
In [192]:
# third argument is the step valuerange(0, 5, 2)
Out[192]:
In [193]:
# Python 2 only: use xrange to create a sequence rather than a list (saves memory)xrange(100, 100000, 5)
Out[193]:
In [194]:
# not the recommended stylefruits = ['apple', 'banana', 'cherry']for i in range(len(fruits)): print(fruits[i].upper())
In [195]:
# recommended stylefor fruit in fruits: print(fruit.upper())
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)
In [197]:
# use enumerate if you need to access the index value within the loopfor index, fruit in enumerate(fruits): print(index, fruit)
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")
In [199]:
count = 0while count < 5: print('This will print 5 times') count += 1 # equivalent to 'count = count + 1'
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]:
In [201]:
# equivalent list comprehensioncubes = [num**3 for num in nums]cubes
Out[201]:
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]:
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]:
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]:
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]:
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]:
In [207]:
# equivalent list comprehensionitems = [item for row in matrix for item in row]items
Out[207]:
In [208]:
fruits = ['apple', 'banana', 'cherry']unique_lengths = {len(fruit) for fruit in fruits}unique_lengths
Out[208]:
In [209]:
fruit_lengths = {fruit:len(fruit) for fruit in fruits}fruit_lengths
Out[209]:
In [210]:
fruit_indices = {fruit:index for index, fruit in enumerate(fruits)}fruit_indices
Out[210]:
In [211]:
simpsons = ['homer', 'marge', 'bart']map(len, simpsons)
Out[211]:
In [212]:
# equivalent list comprehension[len(word) for word in simpsons]
Out[212]:
In [213]:
map(lambda word: word[-1], simpsons)
Out[213]:
In [214]:
# equivalent list comprehension[word[-1] for word in simpsons]
Out[214]:
In [215]:
nums = range(5)filter(lambda x: x % 2 == 0, nums)
Out[215]:
In [216]:
# equivalent list comprehension[num for num in nums if num % 2 == 0]
Out[216]:
1 0
- Python基础知识速查(下)
- Python基础知识速查(上)
- Python基础知识查漏补缺
- python基础知识纵览(下)
- Python基础知识(一)
- Python基础知识(一)
- python学习(基础知识)
- python基础知识(一)
- Python (一)基础知识
- python基础知识(2)
- python基础知识(3)
- Python基础知识(一)
- Python基础知识(二)
- Python 基础知识(1)
- Python基础知识(一)
- python基础知识(一)
- Python(0):Python基础知识
- Python 语法速查
- React Native 安装和初始化踩坑
- 级联查
- 代码中控制布局显示或隐藏
- Fresco 的几个注意的点
- springboot邮件发送功能和两个常见问题
- Python基础知识速查(下)
- TCP协议三次握手和四次挥手
- 集成第三方推送最佳实践
- Shared and Exclusive Locks 共享和排它锁
- Java BigDecimal详解
- Material Design Lite学习(一) 概述及环境搭建
- Android RecyclerView 实现ListView GridView混排
- Docker整理之Docker镜像相关(三)
- 关于mui scroll使用笔记