九宫格、函数、高阶函数、生成式、生成器,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): #第一、二、三排都不等
                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) 直接退出

函数的参数
*args tuple参数,对应赋值
*kwargs dict参数,对应赋值
fun(
args, **kwargs)
fun(1, 2, 3, 4, 5, a=10, b=40)

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:

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

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

结果:reduce:列表里一个个元素通过fun函数相加
15

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)

字典有三种初始化的方法:

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)])

生成器

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的下一行开始

字典排序:

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)

转载于:https://blog.51cto.com/jacksoner/2066211

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值