解释范围(n)和布尔列表,一对一地图,更简单?

时间:2011-01-06 02:10:41

标签: python variable-assignment

#!/usr/bin/python
#
# Description: bitwise factorization and then trying to find
# an elegant way to print numbers

# Source: http://forums.xkcd.com/viewtopic.php?f=11&t=61300#p2195422
# bug with large numbers such as 99, but main point in simplifying it
#
def primes(n):
    # all even numbers greater than 2 are not prime.
    s = [False]*2 + [True]*2 + [False,True]*((n-4)//2) + [False]*(n%2)
    i = 3;
    while i*i < n:
        # get rid of ** and skip even numbers.
        s[i*i : n : i*2] = [False]*(1+(n-i*i)//(i*2))
        i += 2
        # skip non-primes
        while not s[i]: i += 2
    return s


# TRIAL: can you find a simpler way to print them?
# feeling the overuse of assignments but cannot see a way to get it simpler
#
p = 49
boolPrimes = primes(p)
numbs = range(len(boolPrimes))
mydict = dict(zip(numbs, boolPrimes))

print([numb for numb in numbs if mydict[numb]])

我正在寻找的东西,你能让TRIAL变得极为简单吗?有这样的方法吗?

a=[True, False, True]
b=[1,2,3]
b_a                    # any such simple way to get it evaluated to [1,3]
                       # above a crude way to do it in TRIAL

3 个答案:

答案 0 :(得分:2)

对于python2.7 +,您可以使用itertools.compress

itertools.compress(b,a)

例如

>>> from itertools import compress
>>> a=[True, False, True]
>>> b=[1,2,3]
>>> list(compress(b,a))
[1, 3]

否则你可以使用列表理解

>>> [j for i,j in zip(a,b) if i]
[1, 3]

如果要在素数列表中执行此操作,使用枚举可能更简单

>>> primes = [False, False, True, True, False, True]
>>> list(compress(*zip(*enumerate(primes))))
[2, 3, 5]

答案 1 :(得分:0)

您可以使用enumerate以及列表推导来大大简化这一点:

p = 49
print([num for num, isprime in enumerate(primes(p)) if isprime])

答案 2 :(得分:0)

在这里制作一个词典并不是你想要的,因为词汇是无序的。将对保持为对实际上简化了逻辑,因为您可以迭代对,给出两个元素名称,并在理解中使用这些名称。

使用并行索引列表'压缩'列表的Pythonic方法是使用enumerate

因此:

print ([x for (x, y) in enumerate(primes(49)) if y])