while循环和跳过python中的数字

时间:2014-06-07 00:57:33

标签: python list count while-loop

我正在制作一个while循环计数器,我想跳过某些数字,这些数字的值+ 10,+ 20,+ 30 ......等等。这是我到目前为止所尝试的内容:

lstLength = 26
skipNum = [2, 8]

lst = []
count = 0
while len(lst) < lstLength:
    count +=1
    if count == skipNum[0] or count == skipNum[1]:
        continue
    lst.append(count)
print(lst)

我希望结果列表长度为lstLength,同时跳过数字2,8,12,18,22,28,32,38等等......我怎么能这样做?谢谢!

3 个答案:

答案 0 :(得分:5)

使用:

if count % 10 in skipNum:
    continue

%是模数运算符,因此count % 10count的最后一位数。

答案 1 :(得分:0)

这是我的尝试。它将填充您的列表,直到它达到25的长度。它将使用skipNum中的值来忽略值2,8以及2 + 10,2 + 20,...和8 + 10,8 +20,......

lstLength = 26
skipNum = [2, 8]

count = 0
lst = []
while len(lst) < lstLength:
  count += 1

  if count in skipNum:
    continue

  #check if count is equal to 2+10, 2+20, ... or 8+10, 8+20, ... etc. If
  #that's the case, `add` will be `False`

  #map to a list of booleans indicating whether `count = skipNum+(n*10)` for any `n`
  bool_arr = map(lambda x, y: ((count - y) % 10 != 0), skipNum)

  #reduce array of booleans to a single boolean value indicating we can `add`
  add = not any(bool_arr)

  if add:
    lst.append(count)


print(lst)

答案 2 :(得分:0)

为了便于比较,以下是使用itertools函数实现此功能的方法,最终比while循环方法更快:

from itertools import count, ifilter, islice

def iter_filt(black_list, lstLen):
    return list(islice(ifilter(lambda x: x % 10 not in black_list, count(1)), lstLen))

用法:

>> print(iter_filt([2,8], 26))
[1, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 17, 18, 19, 20, 21, 23, 24, 25, 27, 28, 29, 30, 31, 33]

该功能以count(1)开头,从1(1,2,3,4,5,6,...)开始生成一系列无数的数字。然后它通过ifilter运行,过滤掉x % 10 in black_list(由Barmar建议)的任何结果。然后,islice仅用于从lstLen ifiltered迭代器获取第一个count结果。

这样做比while循环方法快一点:

from itertools import count, islice, ifilter
import timeit

def while_filt(skipNum, lstLength):
    lst = []
    count_ = 0 
    while len(lst) < lstLength:
        count_ +=1 
        if count_ % 10 in skipNum:
            continue
        lst.append(count_)
    return lst 



def iter_filt(black_list, lstLen):
    return list(islice(ifilter(lambda x: x % 10 not in black_list, count(1)), lstLen))


if __name__ == "__main__":
    black_list = [2,6]
    length = 1000026
    print timeit.timeit("while_filt(%s,%s)" % (black_list, length),
                  setup="from __main__ import while_filt", number=50)
    print timeit.timeit("iter_filt(%s,%s)" % (black_list, length),
                  setup="from __main__ import iter_filt", number=50)

输出:

dan@dantop2:~$ ./funtimes.py 
15.1266388893  # while_filt
11.8498108387  # iter_filt