如何区分奇数和偶数的列表?

时间:2019-07-13 11:55:29

标签: python-3.7

在python中,我有10个从1到25的随机整数,我想将数字分为两个列表:奇数和偶数。不确定如何解决这个问题。

我已经尝试过使用条件语句来查看它是奇数还是偶数,但是我不知道如何将它们放入两个单独的列表中。

import random
number1 = random.randint(1,25)
number2 = random.randint(1,25)
number3 = random.randint(1,25)
number4 = random.randint(1,25)
number5 = random.randint(1,25)
number6 = random.randint(1,25)
number7 = random.randint(1,25)
number8 = random.randint(1,25)
number9 = random.randint(1,25)
number10 = random.randint(1,25)
if number1 % 2 == 0:
    number1 == 'even'
else:
    number1 == 'odd'
if number2 % 2 == 0:
    number2 == 'even'
else:
    number2 == 'odd'
if number3 % 2 == 0:
    number3 == 'even'
else:
    number3 == 'odd'
if number4 % 2 == 0:
    number4 == 'even'
else:
    number4 == 'odd'
if number5 % 2 == 0:
    number5 == 'even'
else:
    number5 == 'odd'
if number6 % 2 == 0:
    number6 == 'even'
else:
    number6 == 'odd'
if number7 % 2 == 0:
    number7 == 'even'
else:
    number7 == 'odd'
if number8 % 2 == 0:
    number8 == 'even'
else:
    number8 == 'odd'
if number9 % 2 == 0:
    number9 == 'even'
else:
    number9 == 'odd'
if number10 % 2 == 0:
    number10 == 'even'
else:
    number10 == 'odd'

I didn't get any errors, but I don't know what to do.

2 个答案:

答案 0 :(得分:1)

下面的尝试代码,它创建两个数组(一个为奇数,另一个为偶数),并分别向它们添加奇数和偶数:

evenArr = []
oddArr = []
for i in range(0, 10):
  number = random.randint(1,25)
  if number % 2 == 0: #means it is even
    evenArr.append(number)
  else: #otherwise it is odd
    oddArr.append(number)

我希望能有所帮助;

答案 1 :(得分:0)

您可以做到

 num = random.randint(1,25)
 mod = num % 2
 if mod > 0:
     listEvenNumbers.append(mod)
 else:
     listUnevenNumbers.append(mod)

这会将每个数字除以2,如果没有余数(偶数就是这种情况),则将其附加到偶数列表中。如果不是偶数,则会将其追加到不均匀数字列表中。