python 缺失值筛选_python - 如何更简洁地找到缺失值?

Sven的优秀代码只做了太多的工作,并且使用了tuple解包而不是pop()。 此外,它可以添加一个警卫if x != y来检查x和y是不同的。 以下是改进后的答案:

# create the set just once

choices = {'a', 'b', 'c'}

x = 'a'

y = 'b'

# the main code can be used in a loop

if x != y:

z, = choices - {x, y}

以下是与时间套件比较的时间表,以显示相对表现:

import timeit, itertools

setup_template = '''

x = %r

y = %r

choices = {'a', 'b', 'c'}

'''

new_version = '''

if x != y:

z, = choices - {x, y}

'''

original_version = '''

if x == 'a' and y == 'b' or x == 'b' and y == 'a':

z = 'c'

elif x == 'b' and y == 'c' or x == 'c' and y == 'b':

z = 'a'

elif x == 'a' and y == 'c' or x == 'c' and y == 'a':

z = 'b'

'''

for x, y in itertools.product('abc', repeat=2):

print '\nTesting with x=%r and y=%r' % (x, y)

setup = setup_template % (x, y)

for stmt, name in zip([original_version, new_version], ['if', 'set']):

print min(timeit.Timer(stmt, setup).repeat(7, 100000)),

print '\t%s_version' % name

以下是时间的结果:

Testing with x='a' and y='a'

0.0410830974579 original_version

0.00535297393799 new_version

Testing with x='a' and y='b'

0.0112571716309 original_version

0.0524711608887 new_version

Testing with x='a' and y='c'

0.0383319854736 original_version

0.048309803009 new_version

Testing with x='b' and y='a'

0.0175108909607 original_version

0.0508949756622 new_version

Testing with x='b' and y='b'

0.0386209487915 original_version

0.00529098510742 new_version

Testing with x='b' and y='c'

0.0259420871735 original_version

0.0472128391266 new_version

Testing with x='c' and y='a'

0.0423510074615 original_version

0.0481910705566 new_version

Testing with x='c' and y='b'

0.0295209884644 original_version

0.0478219985962 new_version

Testing with x='c' and y='c'

0.0383579730988 original_version

0.00530385971069 new_version

这些时序表明,原始版本的性能会有很大差异,具体取决于各种输入值触发的if语句。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值