Python 十个加快编程效率的技巧

描述

1.交换两个数字

  1. x, y =10,20

  2. print(x, y)

  3. x, y = y, x

  4. print(x, y)

输出

  1. 10 20

  2. 20 10

**

2.反转字符串**

  1. a ="GeeksForGeeks"

  2. print("Reverse is", a[::-1])

输出

  1. Reverse is skeeGroFskeeG

**

3.连接列表中的元素**

  1. a =["Geeks","For","Geeks"]

  2. print(" ".join(a))

输出

  1. GeeksForGeeks

**

4.多比较符**

  1. n =10

  2. result = 1 < n < 20

  3. print(result)

  4. result = 1 > n <= 9

  5. print(result)

输出

  1. True

  2. False

**

5.输出模块的位置**

  1. import os;

  2. import socket;

  3. print(os)

  4. print(socket)

输出

  1. 'os'from'/usr/lib/python3.5/os.py'><>

  2. 'socket'from'/usr/lib/python3.5/socket.py'><>

**

6.使****用枚举**

  1. classMyName:

  2. Geeks,For,Geeks= range(3)

  3. print(MyName.Geeks)

  4. print(MyName.For)

  5. print(MyName.Geeks)

输出

  1. 2

  2. 1

  3. 2

**

7.函数返回多个值**

  1. def x():

  2. return 1,2,3,4

  3. a, b, c, d = x()

  4. print(a, b, c, d)

输出

  1. 1 2 3 4

**

8.找到数组中出现频率最高的数**

  1. test =[1,2,3,4,2,2,3,1,4,4,4]

  2. print(max(set(test), key = test.count))

输出

  1. 4

**
9.检查对象占用内存大小**

  1. import sys

  2. x =1

  3. print(sys.getsizeof(x))

输出

  1. 28

**

10.检查两个字符串是否字谜(字母和出现次数一致)**

  1. from collections importCounter

  2. def is_anagram(str1, str2):

  3. returnCounter(str1)==Counter(str2)

  4. print(is_anagram('geek','eegk'))

  5. print(is_anagram('geek','peek'))

输出

  1. True

  2. False

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分