【问题标题】:Function with zip range带邮编范围的功能
【发布时间】:2018-03-10 20:39:48
【问题描述】:

您好,我想一次进行两次计数,一次从 0 递增,另一次从 100 递减。最终结果应如下所示。左侧从 O 到 100 递增 5,从右侧从 100 到 0 递减 7。

    0    100
    5    93
   10    86
   15    79
   20    72
   25    65
   30    58
   35    51
   40    44
   45    37
   50    30
   55    23
   60    16
   65     9
   70     2
   75     0
   80     0
   85     0
   90     0
   95     0
  100     0
#What I already have
inc = int(input("ENTER THE INCREMENT NUMBER: "))
dec = int(input("ENTER THE DECREMENT NUMBER: "))

def printcounting(inc, dec):
    for m, n in zip([k for k in range(0, 101, inc)], [l for l in range(100, 0, -dec)]):
        print("{} {}".format(m, n))


printcounting(inc,dec)

我想知道如何在右侧打印零,因为使用我已经拥有的程序,它会根据输入值打印。我也很想使用 while 而不是 zip 函数和列表来解决它。

【问题讨论】:

  • OP 似乎需要itertools.zip_longest 用零填充较短的生成器。

标签: python function printing while-loop count


【解决方案1】:

zip 在较短的生成器结束时停止,因此不适合这里。 while 循环在这里会很不合 Python。

您需要使用零填充值的itertools.zip_longest

您还需要删除只会减慢程序速度的无用列表解析,因为它们不会过滤或转换range 发布的数据。

import itertools

inc = 5
dec = 7

for x in itertools.zip_longest(range(0, 101, inc),range(100, 0, -dec),fillvalue=0):
    print("{} {}".format(*x))

结果:

0 100
5 93
10 86
15 79
20 72
25 65
30 58
35 51
40 44
45 37
50 30
55 23
60 16
65 9
70 2
75 0
80 0
85 0
90 0
95 0
100 0

【讨论】:

    【解决方案2】:

    我也很想使用 while 而不是 zip 函数和列表来解决它。

    这是一个没有使用zipitertools.zip_longest的版本:

    In[2]: def print_counting(inc, dec):
      ...:     cnt_1 = 0
      ...:     cnt_2 = 100
      ...:     while True:
      ...:         print('{} {}'.format(cnt_1, cnt_2))
      ...:         if cnt_1 == 100 and cnt_2 == 0:
      ...:             break
      ...:         cnt_1 = min(cnt_1 + inc, 100)
      ...:         cnt_2 = max(cnt_2 - dec, 0)
      ...: 
    In[3]: print_counting(5, 7)
    0 100
    5 93
    10 86
    15 79
    20 72
    25 65
    30 58
    35 51
    40 44
    45 37
    50 30
    55 23
    60 16
    65 9
    70 2
    75 0
    80 0
    85 0
    90 0
    95 0
    100 0
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多