Python: Elegant and efficient ways to mask a list

后端 未结 5 1352
情深已故
情深已故 2020-12-05 14:26

Example:

from __future__ import division
import numpy as np

n = 8
\"\"\"masking lists\"\"\"
lst = range(n)
print lst

# the mask (filter)         


        
5条回答
  •  自闭症患者
    2020-12-05 14:56

    i don't consider it elegant. It's compact, but tends to be confusing, as the construct is very different than most languages.

    As Rossum has said about language design, we spend more time reading it than writing it. The more obscure the construction of a line of code, the more confusing it becomes to others, who may lack familiarity with Python, even though they have full competency in any number of other languages.

    Readability trumps short form notations everyday in the real world of servicing code. Just like fixing your car. Big drawings with lots of information make troubleshooting a lot easier.

    For me, I would much rather troubleshoot someone's code that uses the long form

    print [lst[i] for i in xrange(len(lst)) if msk[i]]
    

    than the numpy short notation mask. I don't need to have any special knowledge of a specific Python package to interpret it.

提交回复
热议问题