Basic Knowledge of Python(1)

Commen used numeric data types

int
float
complex
str

Functions for all kinds of data type

  1. real division: /
  2. ground division: //
  3. modulus: %
  4. exponent: **
  5. +=, -=
  6. round(number, precision) e.g.: round(3.1415, 2) 3.14
  7. sorted
    sorted(I) # return revised values
    sorted(a, key=lambda x:x[0])
    假如a是一个由元组构成的列表,这时候就麻烦了,我们需要用到参数key,也就是关键词,看下面这句命令,lambda是一个隐函数,是固定写法,不要写成别的单词;x表示列表中的一个元素,在这里,表示一个元组,x只是临时起的一个名字,你可以使用任意的名字;x[0]表示元组里的第一个元素,当然第二个元素就是x[1];所以这句命令的意思就是按照列表中第一个元素排序

basic data structure

  1. tuple b = (1, 2.5, ‘data’)
  2. list c =[1, 2.5, ‘data’]
  3. dict d ={‘Name’: ‘Kobe’, ‘Country’: ‘US’}
  4. set e = set([‘u’, ‘d’, ‘ud’]) #unordered collection object of unique objects

functions for str

t = ‘He is a string’
t.capitalize()  	#Cap first letter of the first word
t.title() 				#cap the  first letter of all words
t.upper()  		#cap all letters
t.lower()			#uncap all letter
t.split()				#split by words
t.split(‘.’)			#split by .
t.find(‘i’)			#return index of the first ‘i’
t.find(‘in’)			#index of ‘i’ in ‘in’
t.replace(‘ ‘, ‘|’)  #replace by |
t.strip(‘http://”)	#delete sth
t.join(str)			# Return a string which is the concatenation of the string 
str.index(str, beg=0, end=len(string))	如果包含子字符串返回开始的索引值,否则抛出异常。(similar with find(i))

format用来快速处理处理各种字符串
“{} {}”.format(ct, dom) for dom, ct in ans.items()
#Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces (’{’ and ‘}’).

#通过位置
print(’{0},{1}’.format(‘name’, 20))
print(’{0},{1}’.format(‘name’, 20))
print(’{1},{0},{1}’.format(‘name’, 20))

#通过关键字参数
‘{name},{age}’.format(age=18,name=‘chuhao’)

#通过映射list
a_list = [‘anna’, 20, ‘china’]
print(‘my nam is {0[0]},from {0[2]}, age is {0[1]}’.format(a_list))

#通过映射dict
b_dict = {‘name’ :‘anna’, ‘age’:20,‘province’:‘jiangsu’}
print(‘my name is {name}, age is {age}, from {province}’.format(**b_dict))

#填充与对齐

是否包含字符串
ice_cream= “ice cream”
contains= “ice” in ice_cream # return True or False

functions for list

l = [1, 2]
l.append([3, 4])		#add an element	[1, 2, [3, 4]]
l.extend([3, 4])		#add a list	[1, 2, 3, 4]
l.insert(1, data)		#insert before index
l.append(data)		#insert an element
l.remove(data)		#remove an element
l.sort()				#change l
l.pop()				#get the last data from the list (takes no argument)
l.index(obj)			#get the first index of the obj
l.sort()				#only for list, not for string	no return value, only for l
l + [data]			#append data at the end of l
l + data				#wrong

#create a list
I = [None] * 10
I = range(10)

#multidimensional list
a = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3]]
#multidimensional list is not a matrix. Mathematical operations may lead to the results that you don’t want to see

list(Counter(str).elements())
cmp(x, y) x < y return -1, x == y return 0, x > y return 1

A = [[1, 0], [-3, 1], [-4, 0], [2, 3]]
for i, j in A: enumerate

List Combination 列表解析
S = sum(x for x in A if x % 2 ==0)
[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x!=y]
S += a

使用列表生成式
test = [[0 for i in range(m)] for j in range(n)]
m: number of the column
n: number of the row

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表

*M unpack the original input list M into multiple sublist row
zip aggregate element in the parameter list

all() all is True
any() any is True

functions for dict

l.pop(index)			#pop the data according to the index(must have a index)
l.pop()				# WRONG
l.popitem()			#pop the last item from the list
map(func, *iterables) --> map object
dict[key] = dict.get(key, 0) + 1
dict(Counter(list))

functions for set

s&t intersection
s|t union
set1 – set2 #获取在set1而不在set2中的元素,等于set1.difference(set2)
set1^set2 #获取在set1或set2中存在,但不包括都存在的元素
functions of the set
set.add(x)
set.clear()
set.copy()
set.discard(x) #删除集合中值为x的元素
set1.isdisjoint(set2) #true if disjoint
set1.issubset(set2) #true if set1 is the subset of set2
set1.issuperset(set2)
remove(x) #value x
判断是否在集合内if num1 in set1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值