Python易忘操作总结
Python四大金刚:strings, set, dictionary, list - 增删查改
STRINGS
- str.split(str=’’, num=string.count(str))
- str.replace(old, new, count )
- str.isdigit()
# method1
'animals'.isdigit()
# method2
str.isdigit('animals')
输出为True or False
注意:
1.使用的是str,而不是string
2.由于负数的符号-为string,应该去掉符号再操作
int('-12345') => int("12345")
- print()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
sep: seperated by ’ ’
end: the things prints out at end, ‘\n’ is default
file: the position to print out, may be a file name
(not sure what happens when file does not exist, will it create one automatically?)
DICTIONARY
SET
LIST
- .join()
返回值是一个新的string
str.join(sequence)
注:元素为数字的时候无法join,需转为字符
进阶:与列表解析组合使用
' x '.join(str(n) for n in function(var))
- list.reverse
注意:.reverse反转的是原始列表,返回值为None,不能直接使用返回值,目的是节省空间,.sort同理
- list.pop()
pop出list最后一项并且返回
BASIC OPERATIONS
- max()
- sum()
- min()
LOGIC
- if else
… if … else …
result = 'valid' if x == 1 else result = 'invalid'
if: … else: …
… if else …
- For … in …
if x == 1:
result = 'valid'
else:
result = 'invalid'
- enumerate()
enumerate(sequence, [start=0])
sequence – 一个序列、迭代器或其他支持迭代对象。
start – 下标起始位置。
list(enumerate(seasons, start=1))
################## output #####################
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
- reduce(function, iterable[, initializer])
def add(x, y) :
return x + y
sum1 = reduce(add, [1,2,3,4,5])
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])
print(sum1)
print(sum2)
################################################
# output
15
15