The Secret Name of List Comprehensions
2011-12-02 14:03
295 查看
The Secret Name of List Comprehensions (Python recipe) by Chris Perkins
ActiveState Code (http://code.activestate.com/recipes/204297/)▲ 5 ▼ | Sometimes you want to have a list comprehension refer to itself, but you can't because it isn't bound to a name until after it is fully constructed. However, the interpreter creates a secret name that only exists while the list is being built. That name is (usually) "_[1]", and it refers to the bound method "append" of the list. This is our back door to get at the list object itself. Python, 70 lines Download Copy to clipboard
The temporary name assigned is "_[1]" (or "_[2]" for a nested list comprehension). Since this is not a syntactically valid Python identifier, we cannot refer to it directly - we need to access it as locals()['_[1]']. Then we just use the bound method's __self__ attribute to get at the list object itself. This lets us do all sorts of neat party tricks, like performing "if" tests that involve looking at the items that have already been added to the list - or even modifying or deleting them. This is just what the doctor ordered for finding primes in a one-liner - for each odd number we need to test whether it is divisible by any prime number less than or equal to the square root of the number being tested. Since we already have all the smaller primes stored, and, with our new parlour trick, have access to them, this test is a breeze and requires no auxiliary storage. Note that while the prime number functions above are pretty fast for one-liners (plt(100000) takes 7 seconds on my machine, timed with the ultra-accurate "counting-in-my-head" method), they are nowhere near as fast as the Sieve of Eratosthenes method (recipe 117119). However, they are much, much sexier. ;) And now for the big "but"... It should come as no surprise to anyone that this is a totally undocumented, seat-of-your-pants exploitation of an implementation detail of the Python interpreter. There is absolutely no guarantee that this will continue to work in any future Python release. In fact I only know for sure that it works in Python 2.2.2 and 2.3b1. Beyond that you're on your own. Finally, as an aside, let me just say: itertools rules! >>>1in itertools.imap(lambda x:1/x,[1,0])# Look Ma, no ZeroDivisionError! True (Lazy evaluation makes the primality tests *way* more efficient.) Tags: shortcuts |
相关文章推荐
- The study of List Comprehensions in Python(20170911)
- sql server query to get the list of column name in a table
- The Difference of Class.forName()、Class.forName().newInstance() and New in Java
- How to change the name of logfile dynamically using log4j
- The unique identifier of the win32 class is the class name
- list of the x$ tables
- Invalid ADAPTORNAME specified. Type 'imaqhwinfo' for a list of available ADAPTORNAMEs. Image acquis
- To find names containing exactly five characters, use “^”and “$”to match the beginning and end of the name, and five instances of “.”in between: mysql
- 关于问题The fully qualified name of the bean's class, except if it serves only as a parent definition fo
- This platform could not be created because a solution platform of the same name already exists解决方法
- 苹果审核被拒原因分析 Apps or metadata that mentions the name of any other mobile platform will be rejected
- Warning: Permanently added the RSA host key for IP address '192.30.253.113' to the list of known hos
- The list of vision-based SLAM / Visual Odometry open source projects, libraries, dataset, tools
- whether the results are the same of getClass().getName() called in child class and parent class?
- the secret of starting conversations and making friends
- Myeclipse 保存jsp异常Save FailedCompilation unit name must end with .java, or one of the registered Java-like extensions
- The List of the 100 Companies That Matter Most in Online Video in 2015
- TypeError: view must be a callable or a list/tuple in the case of include()
- A list of the websites I like.
- The content of element type "web-app" must match "(icon?,display-name?,description?,distributable?,c