本篇博文主要是对自己在使用Python过程对这些基础数据结构的常见用法的总结,主要目的是能够方便自己在编写Python程序时,能够随时查看这篇笔记,从而实现快速查询不同基础数据结构基本用法的作用,也希望对大家有所帮助。
列表创建: (1)简单创建
x = [1,2,3] x = [1,"name",10.0] x = list(range(10))(2)列表理解(list comprehension)
nums = [0, 1, 2, 3, 4] squares = [x ** 2 for x in nums] print(squares) # Prints [0, 1, 4, 9, 16] nums = [0, 1, 2, 3, 4] even_squares = [x ** 2 for x in nums if x % 2 == 0] print(even_squares) # Prints "[0, 4, 16]"列表切片(slicing):
nums = list(range(5)) # range is a built-in function that creates a list of integers print(nums) # Prints "[0, 1, 2, 3, 4]" print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]" print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]" print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]" print(nums[:]) # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]" print(nums[:-1]) # Slice indices can be negative; prints "[0, 1, 2, 3]" nums[2:4] = [8, 9] # Assign a new sublist to a slice print(nums) # Prints "[0, 1, 8, 9, 4]"列表遍历: (1)纯元素遍历
animals = ['cat', 'dog', 'monkey'] for animal in animals: print(animal) # Prints "cat", "dog", "monkey", each on its own line.(2)带索引遍历
animals = ['cat', 'dog', 'monkey'] for idx, animal in enumerate(animals): print('#%d: %s' % (idx + 1, animal)) # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line1、对元组中每个元素乘以一个倍数
d = (2, 3) print(d) y = tuple(map(lambda x: x*2, d)) print(y)字典创建: (1)直接创建
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data print(d['cat']) # Get an entry from a dictionary; prints "cute" print('cat' in d) # Check if a dictionary has a given key; prints "True" d['fish'] = 'wet' # Set an entry in a dictionary print(d['fish']) # Prints "wet" # print(d['monkey']) # KeyError: 'monkey' not a key of d print(d.get('monkey', 'N/A')) # Get an element with a default; prints "N/A" print(d.get('fish', 'N/A')) # Get an element with a default; prints "wet" del d['fish'] # Remove an element from a dictionary print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"(2)字典推导式
nums = [0, 1, 2, 3, 4] even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0} print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"字典遍历: (1)直接遍历 得到的是键
d = {'person': 2, 'cat': 4, 'spider': 8} for animal in d: legs = d[animal] print('A %s has %d legs' % (animal, legs)) # Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"(2)利用字典成员函数 items成员函数返回键值对元组
d = {'person': 2, 'cat': 4, 'spider': 8} for animal, legs in d.items(): print('A %s has %d legs' % (animal, legs)) # Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"keys成员函数返回键:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal in d.keys(): print('A %s' % (animal)) # Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"values成员函数返回值:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal in d.values(): print('A %s' % (animal))注意如何限定小数点位数。
【参考】 1、https://cs231n.github.io/python-numpy-tutorial/