九宮格、函數、高階函數、生成式、生成器,passwd的uid排序

九宮格

# #九宮格:
# 1|2|3
# 4|5|6
# 7|8|9
# 橫排相加=15,豎排相加=15,兩對角相加等於15
num=[]
for i in range(1,10):
    num.append(i)
#遍歷x、y,當x!=y時,再遍歷z,x!=z,y!=z,三個數就都不同
L=[(x,y,z) for x in num for y in num if x!=y for z in num if x!=z and y!=z and x+y+z==15]

for L1 in L:
    for L2 in L:
        if set(L1) & set(L2):               #set集合,取出的第一排不能等於第二排
            continue
        for L3 in L:
            if set(L1) & set(L2) & set(L3): #第1、2、三排都不等
                continue
            elif L1[0]+L2[0]+L3[0] != 15:   #豎排不等的話就跳過,橫排確定是相等的,因此不用判斷
                continue
            elif L1[1]+L2[1]+L3[1] != 15:
                continue
            elif L1[1]+L2[1]+L3[1] != 15:
                continue
            elif L1[0]+L2[1]+L3[2] != 15:   #兩對角不等的話就跳過
                continue
            elif L1[2]+L2[1]+L3[0] != 15:
                continue
            else:
                print('''
                    {0}|{1}|{2}
                    {3}|{4}|{5}
                    {6}|{7}|{8}
                    '''.format(L1[0],L1[1],L1[2],L2[0],L2[1],L2[2],L3[0],L3[1],L3[2]))

函數

def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)算法

f(2)
#輸出什麼[0, 1]

f(3,[3,2,1])
#結果: [3, 2, 1, 0, 1, 4]

f(x=3, l=[])
#結果: [0, 1, 0,1,4]

函數的額關鍵字:
def 定義函數
return 返回這,後面代碼不執行
pass 濾過
exit(1) 直接退出app

函數的參數
*args tuple參數,對應賦值
*kwargs dict參數,對應賦值
fun(
args, **kwargs)
fun(1, 2, 3, 4, 5, a=10, b=40)ide

def fun(a,*args,**kwargs):
    print('a={0}\nargs={1}\nkwargs={2}\n'.format(a,args,kwargs))
fun(1,2,3,4,5,k=1,b=2)
結果:
a=1
args=(2, 3, 4, 5)
kwargs={'b': 2, 'k': 1}

高階函數

都是能夠經過代碼邏輯實現的。
都是能夠經過代碼邏輯實現的
可是你寫的函數的負責程序,或者算法不必定有人家內置的好函數

reduce:code

from functools import reduce
def fun(x,y):
    return x+y

print(reduce(fun,[1,2,3,4,5]))

結果:reduce:列表裏一個個元素經過fun函數相加
15orm

map:
def fun(x):
    return x*2

for i in map(fun,[1,2,3,4,5]):
    print(i)

結果:map在列表裏每個元素遍歷
2
4
6
8
10

惟一用的比較多的,就是sorted:排序

sorted(iterable, key, reverse)
print(sorted([1, 4, 342, 3, 45, 76, 435, 34], reverse=True)

字典有三種初始化的方法:it

d1 = dict(a=1, b=2)
d2 = {"a": 1, "b": 2}
d3 = dict([("a", 1), ("b", 2)])
print(d1, d2, d3)

生成式

print([x for x in range(10)])form

生成器

def test():
    a = 1
    for i in range(1, 10):
        yield i
        #return i
        a += 1
        #return i
    print(a)
for i in test():
    print(i)

#return和yield的區別
#return 返回一次就退出函數
#yiele 每次都返回,可是下一次取值時,從上一次yield的下一行開始class

字典排序:

import codecs

with codecs.open('passwd', 'r') as f:
    l=sorted(f.readlines(), key=lambda item:int(item.split(':')[2]))
with codecs.open('sortPasswd', 'w') as f:
     f.writelines(l)