>>> def quicksort(arr):
if len(arr)<=1:
return arr
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
>>> del d['fish'] # 删除元素
>>> print(d.get('fish','N/A'))
N/A
字典循环
>>> d = {'person':2,'cat':4,'spider':8}
>>> for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal,legs))
A person has 2 legs
A cat has 4 legs
A spider has 8 legs
# 获取键值和相应值可以使用items方法
>>> d = {'person':2,'cat':4,'spider':8}
>>> for animal,legs in d.items():
print('A %s has %d legs' % (animal,legs))
A person has 2 legs
A cat has 4 legs
A spider has 8 legs
字典推导式Dictionary comprehensions
>>> d = {'person':2,'cat':4,'spider':8}
>>> 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)
{0: 0, 2: 4, 4: 16}
集合
集合是一个无序不重复元素集。
集合基本操作
>>> animals = {'cat','dog'} # 定义集合
>>> print('cat' in animals) # 判断cat是否在集合内
True
>>> print('fish' in animals) # 判断fish是否在集合内
False
>>> animals = {'cat','dog','fish'}
>>> for idx,animal in enumerate(animals):
print('#%d: %s' % (idx+1,animal))
#1: dog
#2: cat
#3: fish
集合推导式Set comprehensions
>>> from math import sqrt
>>> nums = {int(sqrt(x)) for x in range(30)}
>>> print(nums)
{0, 1, 2, 3, 4, 5}
元组
元组是一个(不可变的)有序的值列表。元组在许多方面与列表相似,最重要的区别之一是,元组可以用作字典中的键,也可以作为集合的元素,而列表则不能。