Python实现的经典的quicksort算法例子:
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)
print ( quicksort ([3,6,8,10,1,2,1]) )
基本数据类型
```python
x =3
print ( type (x) ) #<class 'int'>
print(x) #3
print(x+1) #4
print(x-1) #2
print(x*2) #6
print(x**2) #9
x+=1
print(x) #4
x*=2
print(x) #8
y=2.5
print ( type (y) ) #<class 'float'>
print(y,y+1,y*2,y**2) #2.5 3.5 5.0 6.25
需要注意的是,Python中没有 x++ 和 x-- 的操作符。
Python也有内置的长整型和复杂数字类型,具体细节可以查看文档。
布尔型:Python实现了所有的布尔逻辑,但用的是英语,而不是我们习惯的操作符(比如&&和||等)。
t = True
f = False
print (type(t)) # <class 'bool'>
print (t and f) # False
print (t or f) # True
print (not t) # False
print (t != f) # True
字符串:Python对字符串的支持非常棒。
hello ="hello"
world ="world"
print(hello)
print(len(hello))
hw=hello+' '+world
print(hw)
hw2= '%s %s %d' % (hello, world, 12)
print(hw2)
列表Lists
列表就是Python中的数组,但是列表长度可变,且能包含不同类型元素。
xs = [3, 1, 2] # Create a list
print (xs,xs[0],xs[2]) # Prints "[3, 1, 2] 2"
print (xs[-1]) # Negative indices count from the end of the list; prints "2"
print (xs[-2])
print (xs[-3])
xs[2] = 'foo' # Lists can contain elements of different types
print (xs) # Prints "[3, 1, 'foo']"
xs.append('bar') # Add a new element to the end of the list
print (xs) # Prints
x = xs.pop() # Remove and return the last element of the list
print (x, xs) # Prints "bar [3, 1, 'foo']"
切片Slicing:为了一次性地获取列表中的元素,Python提供了一种简洁的语法,这就是切片。
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]"
在Numpy数组的内容中,我们会再次看到切片语法。
循环Loops:我们可以这样遍历列表中的每一个元素:
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print (animal)
# Prints "cat", "dog", "monkey", each on its own line.
如果想要在循环体内访问每个元素的指针,可以使用内置的enumerate函数
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 line
列表推导List comprehensions:在编程的时候,我们常常想要将一种数据类型转换为另一种。下面是一个简单例子,将列表中的每个元素变成它的平方。
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print (squares) # Prints [0, 1, 4, 9, 16]
使用列表推导,你就可以让代码简化很多:
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]
字典Dictionaries
字典用来储存(键, 值)对,这和Java中的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"