python 小白应该知道的小skills

python 作为目前主流的机器学习语言,在此小编插入一个适应机器学习的语言Julia,最近小编亲自学习了一下,被Julia的强大所震惊,Julia可以看成是一门开源聚合多数语言优点的一门编程语言,Julia同时拥有C的速度和Ruby的灵活,也有像Matlab这样的浅显熟悉的数学符号,也是一门像Python的通用语言,也像R语言一样易于统计,具备强大的线性代数。
一.链式比较
直接在print中进行比较,更加人性化。
注:python中不可以直接打印带赋值的变量。

b=5
print(b==3)
print(b==5)
print(1<b<6)
print(1<b==6<6)

运行分别得到下列结果:由于Python中比较运算符的优先级为:<,<=,>,>=,!=,=。故上述最后一个print命令优先执行比较,故得到的结果为False.

False
True
True
False

二.函数链式调用

def mult(a,b):
    return a*b
def add(a,b):
    return a-b

b=False
#注意点
print((mult if b else add)(4,7))
print(mult(4,7))

三.交换变量
简单粗暴

a,b=4,5
a,b=b,a
print(a,b)

四.查找list中出现次数最多的元素
max(iterable, key, default) 求迭代器的最大值,其中iterable 为迭代器,max会for i in … 遍历一遍这个迭代器,然后将迭代器的每一个返回值当做参数传给key=func 中的func(函数表达式) ,然后将func的执行结果传给key,然后以key为标准进行大小的判断。
不易理解的表达式

max((1,3),[1,1],key = lambda x : x[0]) #指定key为返回序列索引0位置的元素后,可以取最大值

任何时候别忘记找一下是否存在相应的内置库
下列表述方法果断简直。

from collections import Counter
a=[1,2,3,4,5,2,1,1,1,2,3]
#计算各个元素的个数,也可用于比较两个字符串是否相等
cnt=Counter(a)
#3代表求出出现次数前三个数
print(cnt.most_common(3))

输出结果:[(1, 4), (2, 3), (3, 2)]
五.将list中的所有元素转为单个字符串
join()函数

语法: ‘sep’.join(seq)

参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串
os.path.join()函数

语法: os.path.join(path1[,path2[,……]])

扫描二维码关注公众号,回复: 4724483 查看本文章

返回值:将多个路径组合后返回

a=["python","is","awesome"]
print(" ".join(a))

六.切片法
例如我们取随机数从1到100 的 8的倍数,函数及结果如下:
个人认为较为广泛的应用最好动一下脑子

#第一个中括号为取8的倍数,第二个为取前四个数
for i in range(1,100)[7::8][:4]:
    print(i)

七.神奇的 for…….else语法
官方文档中的解释:

>When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.

>A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.

https://docs.python.org/2/reference/compound_stmts.html#the-for-statement

换句话说,也就是说当迭代对象执行完并且为空的情况下,才执行else子语句,如果存才break,则直接结束。
实例如下:

a=[1,2,3,4,5]
for el in a:
    if el==0:
        break
else:
    print("asdfasfsad")

if语句没有成立条件,则迭代完之后执行else子语句。
八.合并字典

a1={'a':1}
a2={'b':2}
print({**a1,**a2})

九.寻找list中的最大最小索引

lst=[40,10,30,56]

def minIndex(lst):
    return min(range(len(lst)),key=lst.__getitem__)
def maxIndex(lst):
    return max(range(len(lst)),key=lst.__getitem__)
print(maxIndex(lst))
print(minIndex(lst))

十.去除重复项
与set()函数结合

a=[3,3,32,1,5,5,4,3]
lst=list(set(a))
print(lst)
print(min(range(len(lst)),key=lst.__getitem__))

猜你喜欢

转载自blog.csdn.net/zx_zhang01/article/details/81914740