深入一步探索Python计算身份证校验位的代码写法【map -> imap】,,根据身份证末位的校验
深入一步探索Python计算身份证校验位的代码写法【map -> imap】,,根据身份证末位的校验
根据身份证末位的校验位计算方法,写出了python版的。
根据别人写的一个修改得到:
用到map, zip, sum
#!/usr/bin/env pythondef check_bit( string ): s = map( int, string ) a = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] b = sum( map( lambda x: x[0]*x[1], zip(a, s) ) ) c = b % 11 d = [‘1‘, ‘0‘, ‘x‘, ‘9‘, ‘8‘, ‘7‘, ‘6‘, ‘5‘, ‘4‘, ‘3‘, ‘2‘] return d[c] if __name__ == ‘__main__‘: print check_bit(‘22132119880830001‘) # 1 print check_bit( ‘32010519820927512‘ ) # 7可是一点都不pythonic,于是修改函数成:
check_bit = lambda string: ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'][sum( map( lambda x: x[0]*x[1], zip([7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], map( int, string )) ) ) % 11]
顺水推舟,原来的代码写成一句话:
print repr( map( lambda string: ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'][sum( map( lambda x: x[0]*x[1], zip([7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], map( int, string )) ) ) % 11], ('22132119880830001', '32010519820927512') ) )
在引入itertools模块后,又写了下面几种:
imap + izip +sum (imap产生迭代器,map产生列表)
print repr( [ i for i in imap( lambda string: ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'][sum( imap( lambda x: x[0]*x[1], izip([7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], imap( int, string )) ) ) % 11], ('22132119880830001', '32010519820927512') )] )
或
print repr(list( imap( lambda string: ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'][sum( imap( lambda x: x[0]*x[1], izip([7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], imap( int, string )) ) ) % 11], ('22132119880830001', '32010519820927512') ) ))
imap + reduce + chain
print repr( [ i for i in imap( lambda string: ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'][ reduce( lambda x,y: x+y, imap( lambda x,y: x*int(y), [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], chain( string ) ) ) % 11], ('22132119880830001', '32010519820927512') )] )
starmap +reduce + izip (string需要写成*string)
print repr( [ i for i in starmap( lambda *string: ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'][reduce( lambda x,y: x+y, starmap( lambda x,y: x*y, izip([7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], starmap( int, string )) ) ) % 11], ['22132119880830001', '32010519820927512'] )] )
深入一步探索Python计算身份证校验位的代码写法【map -> imap】,布布扣,bubuko.com
深入一步探索Python计算身份证校验位的代码写法【map -> imap】
相关内容
- Python [练习题] :字典扁平化,,字典扁平化习题:将以
- python从0到1--01.python中的输入/输出(基础篇),,1.prin
- Python常用第三方库,,Pillow图像处理
- Python基础之方法,,class woma
- python3基础13(format的使用),,#!/usr/bin
- python-xpath定位方法详解,,一、xpath基本定
- 程序员为什么要学python,,如果你做很多在电脑上
- python_面向对象——对象之间的关联关系,,1.将类中的对
- Python时间模块(二)----时间日期格式化符号,,python中时间
- Python多线程同步,,对Python多线程
评论关闭