▍1、交换两个变量
# a = 4 b = 5 a,b = b,a # print(a,b) >> 5,4
2、多个变量赋值
a,b,c = 4,5.5,'Hello' #print(a,b,c) >> 4,5.5,hello
a,b,*c = [1,2,3,4,5] print(a,b,c) > 1 2 [3,4,5]
▍3、列表中偶数的和
a = [1,2,3,4,5,6] s = sum([num for num in a if num%2 == 0]) print(s) >> 12
▍4、从列表中删除多个元素
# Deleting all even a = [1,2,3,4,5] del a[1::2] print(a) >[1, 3, 5] a
▍5、读取文件
lst = [line.strip() for line in open('data.txt')] print(lst)
list(open('data.txt')) ##Using with will also close the file after use with open("data.txt") as f: lst=[line.strip() for line in f] print(lst)
▍6、将数据写入文件
with open("data.txt",'a',newline='\n') as f: f.write("Python is awsome")
▍7、创建列表
lst = [i for i in range(0,10)] print(lst) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] or lst = list(range(0,10)) print(lst)
lst = [("Hello "+i) for i in ['Karl','Abhay','Zen']] print(lst) > ['Hello Karl', 'Hello Abhay', 'Hello Zen']
▍8、映射列表或类型转换整个列表
list(map(int,['1','2','3'])) > [1, 2, 3] list(map(float,[1,2,3])) > [1.0, 2.0, 3.0] [float(i) for i in [1,2,3]] > [1.0, 2.0, 3.0]
▍9、创建集合
# Square of all even numbers in an range {x**2 for x in range(10) if x%2==0} > {0, 4, 16, 36, 64}
▍10、Fizz Buzz
['FizzBuzz' if i%3==0 and i%5==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else i for i in range(1,20)]
▍11、回文
text = 'level' ispalindrome = text == text[::-1] ispalindrome > True
▍12、用空格分隔的整数到一个列表
lis = list(map(int, input().split())) print
▍13、Lambda函数
# Function that returns square of any number sqr = lambda x: x * x sqr(10) > 100
▍14、检查列表中数字的存在
num = 5 if num in [1,2,3,4,5]: print('present') > present
▍15、打印图案
n = 5 print('\n'.join('