Python基础知识回顾(也可以说有点小技巧性的东西)

交换变量

a,b=2,3
a,b=b+1,a
print(a,b)
结果如下:
4 2

字典推导和集合推导

some_list=[1,2,3,4,5,6]
another_list=[i+1 for i in some_list]   #列表的推导
print(another_list)
结果如下:
[2, 3, 4, 5, 6, 7]
-------------------------------------------------------
even_set={x for x in some_list if x%2==0}   #集合的推导
print(even_set)
结果如下:
{2, 4, 6}
-------------------------------------------------------
d={x:x%2==0 for x in range(1,11)}   #字典的推导
print(d)
结果如下:
{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}
#注意上面的结果返回值
-------------------------------------------------------
som_list=["English","China","US","Japan"]
mydict={key:value for key,value in enumerate(som_list)}    #字典的推导
print(mydict)
结果如下:
{0: 'English', 1: 'China', 2: 'US', 3: 'Japan'}

计数时使用Counter

from collections import Counter   #需要从collections 模块中引入Counter
c="hello world"   
c=Counter("hello world")   #统计字符串中各个字符出现的次数
print(c)
print(type(c))
print(c.most_common(3))
结果如下:
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
<class 'collections.Counter'>
[('l', 3), ('o', 2), ('h', 1)]

写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”,对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。

for x in range(1,101):
    print("fizz"[x % 3 * len('fizz')::] + "buzz"[x % 5 * len('buzz')::] or x)
    #这里用到了[start:end:len]操作,结果太长,自行测试

同时遍历两个序列

nfc=["hello","hi"]
afc=["john","robot"]
combine=zip(nfc,afc)
for tema,temb in zip(nfc,afc):
    print(tema+":"+temb)
for tema,temb in combine:  #这个和上面那条语句效果一样
    print(tema+":"+temb)
结果如下:
hello:john
hi:robot
hello:john
hi:robot

用乘法初始化列表的值

items=["hello"]*3
items=[0]*3
print(items)
结果如下:
[0, 0, 0]

列表转化为字符串

teams=["Jordon","Micheal","Kebi"]
print(",".join(teams))
结果如下:
Jordon,Micheal,Kebi
-------------------------------------------
num=[i for i in range(5)]    
print(",".join(num))     #join()只能作用于字符串,这样会出错,自行测试

从字典中取元素

data={1:"Tech",2:"Py"}
#data[3]直接取字典中的关键字,可能由于关键字的不存在而导致出错
#稳妥的方法使用try/except,尽管他不尽优雅
try:
    temp=data[3]
except KeyError:
    temp=False
----------------------------------------------------------
#优雅的取值方法
temp=data.get(3,None)
print(temp)
结果如下:
None

求一个序列所有组合的可能的种数

from itertools import combinations
teams=["hello","world","China","US"]
for combines in combinations(teams,3):   #这个3只是一个参数,你输入不大于列表长度的数均可
    print(combines)
结果如下:
('hello', 'world', 'China')
('hello', 'world', 'US')
('hello', 'China', 'US')
('world', 'China', 'US')

猜你喜欢

转载自blog.csdn.net/qq_41621362/article/details/84979457