Python小白的零碎记录

1

3.7往后iterable 、iterator包都包含在collections.abc中了,记录一下

from collections.abc import Iterable,Iterator
print(isinstance((),Iterable))

2

int进制转换:hex() int() oct() bin()
分别16、10、8、2进制
另外:int()函数可以指定原数据进位,如原数据为’101’,不指定为2进制,int()会得到101

//int()函数的说明:
class int(x)
int([x]) -> integer int(x, base=10) -> integer
print(int('101'))
得到:101(默认十进制)
print(int('101',2))
得到:5

3

5/2=2.5
5//2=2

4

随机数

import random
random.randint(a,b)

5

i=1
for i in range(1,8)
//出去后i等于7,不等于8!!!

6 list str互转

split函数:对字符串以指定字符进行切片,以列表形式返回

>>> str
'1 2 3 4 5'
>>> str.split(' ')
['1', '2', '3', '4', '5']

join函数:对iterable以制定字符分割进行连接,返回str,注意iterable中的元素必须是str类型的

>>> tu=(1,2,3,4)
>>> ' '.join(tu)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>>
>>> tu=('1','2','3','4')
>>> '*'.join(tu)
'1*2*3*4'
>>>

7 zip函数可将多个iterable捏在一起进行遍历

name = ['wl','lyf','hg']
old = [22,33,35]
sex=['f','m','f']
for x,y,z in zip(name,old,sex):
    print('{} is {} and {}'.format(x,y,z))

8 大小写转换函数

>>> s
'qWeR sDfG'
>>> s
'qWeR sDfG'
>>> s.upper()
'QWER SDFG'
>>> s.lower()
'qwer sdfg'
>>> s.capitalize()
'Qwer sdfg'
>>> s.title()
'Qwer Sdfg'
>>>

9 reduce函数

将sequence中每两个元素进行function运算,返回结果再和下一个元素继续function运算直到返回最后结果

def reduce(function, sequence, initial)
reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
 from left to right, so as to reduce the sequence to a single value. 
 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). 
 If initial is present, it is placed before the items of the sequence in the calculation, 
 and serves as a default when the sequence is empty.
from functools import reduce
def str2float(s):
    index=s.index('.')
    p=s.replace('.','')
    return reduce(lambda x,y:x*10+y,map(int,p))/(10**(len(s)-index-1))
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

10

一个类里的成员函数不许重名,和C++不一样阿!

11

对字符串进行处理,只要字符[for x in s if x.isalpha()]
只要数字.isdigit()
数字or字母.isalnum()

posted @ 2019-06-06 15:31  NeoZy  阅读(154)  评论(0编辑  收藏  举报