Python 列表与字典
1 列表(Lists)
列表其实就是Python的数组,它支持动态调整大小,并且可以包含不同类型的元素。
a = []
-
列表的常用方法包括
count(key)
,index(value)
,reverse()
,sort()
,append(value)
,pop()
-
切片操作:
nums = list(range(5))
print(nums) # [0, 1, 2, 3, 4]
print(nums[2:4]) # [2, 3]
print(nums[2:]) # [2, 3, 4]
print(nums[:2]) # [0, 1]
print(nums[:]) # [0, 1, 2, 3, 4]
print(nums[:-1]) # [0, 1, 2, 3]
nums[2:4] = [8, 9]
print(nums) # [0, 1, 8, 9, 4]
- 列表推导式
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares) # [0, 4, 16]
1 字典(Map)
Python中的字典类似于C++中的Map。
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"
访问字典的方式
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
print('{:s} has {:d} legs'.format{animal, legs})