基本参考于standford大学cs231n课程笔记cs231n-python numpy tutorial
略有删减与补充,欢迎交流指正
这一部分主要介绍python基本数据类型,学习过python基本语法的可不用看了
基本数据类型
1. 数字与数学运算
x = 3
print type(x) # Prints "<type 'int'>"
print x # Prints "3"
print x + 1 # Addition; prints "4"
print x - 1 # Subtraction; prints "2"
print x * 2 # Multiplication; prints "6"
print x ** 2 # Exponentiation; prints "9"
x += 1
print x # Prints "4"
x *= 2
print x # Prints "8"
#注意!!! python中无x++ x--
y = 2.5
print type(y) # Prints "<type 'float'>"
print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25"
2. 布尔型数据
t = True
f = False
print type(t) # Prints "<type 'bool'>"
print t and f # Logical AND; prints "False"
print t or f # Logical OR; prints "True"
print not t # Logical NOT; prints "False"
print t != f # Logical XOR; prints "True"
3. 字符串
3.1 字符串的基本操作
hello = 'hello' # String literals can use single quotes
world = "world" # or double quotes; it does not matter.
print hello # Prints "hello"
print len(hello) # String length; prints "5"
hw = hello + ' ' + world # String concatenation
print hw # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting
print hw12 # prints "hello world 12"
3.2 字符串操作相关的函数
print s.capitalize() # Capitalize a string; prints "Hello"
print s.upper() # Convert a string to uppercase; prints "HELLO"
print s.rjust(7) # Right-justify a string, padding with spaces; prints " hello"
print s.center(7) # Center a string, padding with spaces; prints " hello "
print s.replace('l', '(ell)') # Replace all instances of one substring with another;
# prints "he(ell)(ell)o"
print ' world '.strip() # Strip leading and trailing whitespace; prints "world"
复合数据类型
4. 列表
列表就是Python中的数组,但是列表长度可变,且能包含不同类型元素
4.1 列表的创建与索引
xs = [3, 1, 2] # Create a list
print xs, xs[2] # Prints "[3, 1, 2] 2"
print xs[-1] # Negative indices count from the end of the list; prints "2"
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']"
4.2 对列表进行切片操作
nums = 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, 8, 4]"
4.3 循环
#循环
countries = ['China','America','Japan']
for country in countries:
print country
'''
China
America
Japan
'''
for idx,country in enumerate(countries):
print '%d:%s' %(idx+1,country)
'''
1:China
2:America
3:Japan
'''
4.4 使用用列表推导式
#使用列表推导
nums = range(5) #[0,1,2,3,4]
squares = [a**2 for a in nums]
print squares #[0, 1, 4, 9, 16]
#添加条件的列表推导
nums = range(5)
even_squares = [a**2 for a in nums if(a%2==0)]
print even_squares #[0, 4, 16]
5. 字典
字典用来储存(键, 值)对,跟java里面的map(key,value)差不多
5.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"
#防止keyerror错误 很重要的技巧
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"
5.2 字典循环
- 只访问键
d = {'person':2,'cat':4,'apider':8}
for animal in d:
print 'A %s has %d legs' %(animal,d[animal])
- 访问键和值
for animal,legs in d.iteritems():
print 'A %s has %d legs' %(animal,legs)
'''
A person has 2 legs
A apider has 8 legs
A cat has 4 legs
'''
5.3 使用字典推导式
nums = range(5)
y = {x:x**2 for x in nums if x%2==0}#{0: 0, 2: 4, 4: 16}
6. 集合
集合是不同个体的无序集合
6.1 集合的基本操作
animals = {'cat', 'dog'}
print 'cat' in animals # Check if an element is in a set; prints "True"
print 'fish' in animals # prints "False"
animals.add('fish') # Add an element to a set
print 'fish' in animals # Prints "True"
print len(animals) # Number of elements in a set; prints "3"
animals.add('cat') # Adding an element that is already in the set does nothing
print len(animals) # Prints "3"
animals.remove('cat') # Remove an element from a set
print len(animals) # Prints "2"
6.2 集合中的循环
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print '#%d: %s' % (idx + 1, animal)
# Prints "#1: fish", "#2: dog", "#3: cat"
6.3 使用集合推导式
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print nums # Prints "set([0, 1, 2, 3, 4, 5])"
7. 元组
与列表类似 不同的是元组中的值不可改变,元祖可以在字典中用作键,可以作为集合的元素,列表不行
d = {(x,x+1): x for x in range(10)}
print d #{(0, 1): 0, (1, 2): 1, (6, 7): 6, (5, 6): 5, (7, 8): 7, (8, 9): 8, (4, 5): 4, (2, 3): 2, (9, 10): 9, (3, 4): 3}
t = (5,6) #creat a tuple
print type(t) #<type 'tuple'>
print d[t] #5
print d[(1,2)] #1
8. 函数
python使用def创建函数,很简单,如下
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print sign(x)
# Prints "negative", "zero", "positive"
带关键字参数的函数,下列中第二个参数为关键字参数,也称可选参数
def hello(name, loud=False):
if loud:
print 'HELLO, %s' % name.upper()
else:
print 'Hello, %s!' % name
hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True) # Prints "HELLO, FRED!"
9. 类
class Greeter(object):
#构造函数
def __init__(self,name):
self.name = name
#实例方法
def greet(self,loud=False):
if loud:
print 'HELLO,%s' %self.name.upper()
else:
print 'Hello,%s' %self.name
g = Greeter('Fred') # Construct an instance of the Greeter class
g.greet() # Call an instance method; prints "Hello, Fred"
g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"