Python 基本数据类型
基本数据类型:
Numbers:
包含 Int 和 float
x =3 print(x) # result: 3 x = 3.14 print(x) # result: 3.14
加减乘除:
a = 6.28 print(a+1) # result: 6.28 print(a-5) # result: 1.2800000000000002 小数的精度问题,在这里不做赘述 print(a*2) # result: 12.56 print(a/2) # result: 3.14 b=3 print(b**3) # result: 27
c=5 c +=1 print (c) #result:6
Python 不支持c++或者c--的操作
Booleans:Python 支持所有的逻辑操作,但是python语言直接用英文单纯而不是&&或者||的符号
t = True f = False print(type(t)) # Prints "<class '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"
Strings:Python特别好的支持string类型
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"
另外String对象还有很多有用的方法
s = "hello" 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"
容器:lists, dictionaries, sets 和tuples
Lists:list 相当于数组,但是他是被序列号的,可以包括不同数据类型的集合
x = [3,2,6] print(x,x[2]) #result: print print(x[-1]) # = x[2] index从后往前 result: 6 x[2]='foo' # list 可以包括不能数据类似的值 print(x) # result: [3, 2, 'foo'] x.append('bar') # list后面追加新元素 print(x) # result: [3, 2, 'foo'] x1= x.pop() # 从x list中出栈,指赋给x1 print(x,x1) # result [3, 2, 'foo'] bar
Slicing:切片
nums = list(range(5)) # range() 函数创建一个 int list print(nums) # result: [0, 1, 2, 3, 4] print(nums[2:4]) # result: [2, 3] 返回一个切片从 index 2 to 4 但不包含4 print(nums[2:]) # result: [2, 3, 4] 返回一个切片从 index 2 to end print(nums[:2]) # result: [0, 1] 返回一个切片从 index 0 to index, 但不包含index 本身 print(nums[:]) # result: [0, 1, 2, 3, 4] 返回全部 print(nums[:-1]) # result: [0, 1, 2, 3] 返回全部最后一个,不包含 nums[2:4]=[8,9] # 分别赋值一个切片从 index 2 to 4 但不包含4 print(nums) # result: [0, 1, 8, 9, 4]
Loops:
animals = ['cat','dog','monkey'] for animal in animals: print(animal) # Prints "cat", "dog", "monkey"
可以用enumerate 函数遍历出元素的位置。
animals = ['cat','dog','monkey'] for idx, animal in enumerate(animals): print('#%d: %s' % (idx+1,animal)) # Prints "#1: cat", "#2: dog", "#3: monkey"
List comprehensions:
nums = [0,1,2,3,4,5] squares =[] for x in nums: squares.append(x**2) print(squares)# result:[0, 1, 4, 9, 16, 25]
你可以用 list comprehensions 实现
nums = [0,1,2,3,4,5] squares =[x**2 for x in nums] print(squares) # result: [0, 1, 4, 9, 16, 25]
list comprehensions也可以加一些条件
nums = [0,1,2,3,4,5] squares =[x**2 for x in nums if x % 2 == 0] print(squares) # result: [0, 4, 16]
Dictionaries
Dictionary 储存(key,value)对,类似java的的map,js中的object
d = {'cat':'cute','dog':'furry'} print(d['cat']) # result: cute print('cat' in d) # 检查 元素是否包含在dic内,结果只能是true false d['fish'] = 'wet' #print(d['sleep']) # key error 'sleep' not a key of d print(d.get('sleep','N/A')) # 拿到一个key为sleep default value 是N/A print(d.get('fish','N/A')) # 拿到一个key为fish default value 是N/A,如果value,显示,所以结果‘wet’ del d['fish'] # 删除一个元素 print(d.get('fish','N/A'))
Loops:
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"
如果要进入dics 中的key和value 分别值,用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"
Dictionary comprehensions:
d = {'person':2,'cat':4,'spider':8} #square = {k:v for (k,v)) in d.items()} dict1_keys = {k*2:v**2 for (k,v) in d.items()} print(dict1_keys) {'personperson': 4, 'catcat': 16, 'spiderspider': 64}
Sets
一个无序的不同元素的集合
animals = {'cat','dog'} print('cat' in animals) # 查看元素是否在集合中 True, False print('fish' in animals) # False animals.add('fish') print('fish' in animals) # Ture print(len(animals)) # 3 animals.add('cat') # 增加一个已经存在的元素对集合没有影响 print(len(animals)) #3 animals.remove('cat') print(len(animals)) #2
Loops:从下面结果就可以清楚了看出sets是无序的
animals = {'cat','dog','fish'} for idx,animal in enumerate(animals): print('#%d: %s' % (idx + 1, animal)) # #1: dog #2: cat #3: fish
Set comprehensions
animals = {'cat','dog','fish'} a = {animal*2 for animal in animals} print(a) #{'fishfish', 'catcat', 'dogdog'}
Tuples:tuple 是可以认为一个有序的list,用法基本和List一样,一个不一样的地方是:tuple能像dict一样用key使用
d = {(x, x + 1): x for x in range(10)} # Create a dictionary with tuple keys print(d) #{(0, 1): 0, (1, 2): 1, (2, 3): 2, (3, 4): 3, (4, 5): 4, (5, 6): 5, (6, 7): 6, (7, 8): 7, (8, 9): 8, (9, 10): 9} t = (5, 6) # Create a tuple print(type(t)) # Prints "<class 'tuple'>" print(d[t]) # Prints "5" print(d[(1, 2)]) # Prints "1"