当我在Python 3中使用zip()函数时,我正在“丢失”值

时间:2017-02-17 11:50:37

标签: python list sorting printing python-3.6

当我运行以下代码时,我似乎“失去”了价值,但我不确定为什么。有没有其他方法可以打印出彼此相邻的两个列表?

我想要做的是在long中创建一个来自用户输入的整数列表。然后应按升序将它们分为正值和负值。

原始代码是:

import numpy as np
import random
print( "(This will create a list of integers, UserInput long. Then separate"     
 "\nthem into positive and negative values in ascending order.)")

userI = input("\nHow many integers would you like, between the values of -100 and 100?: ")

userI = int(userI)

Ints = []

for A in range(userI):
    Ints.append(random.randint(-100, 100))

print('\n', len(Ints))

def quad(N):
    Ints_pos = []
    Ints_neg = []
    for B in N:
        if B >= 0:
            Ints_pos.append(B)
        else:
            Ints_neg.append(B)

    return (Ints_pos, Ints_neg)

pos, neg = quad(N = Ints)

pos = sorted(pos)
neg = sorted(neg, reverse=True)

print('\nPositive', '             Negative'
  '\nValues:',  '              Values:')


for C, D in zip(pos, neg):
    print('-> ', C, '               -> ', D)

input("\nPress 'Enter' to exit")

1 个答案:

答案 0 :(得分:5)

请注意,使用zip时:

  

当最短输入可迭代用尽时,迭代器停止。

您应该考虑使用itertools.zip_longest并提供虚拟值来填充较短的可迭代。