列表中的Python偶/奇值

问题描述 投票:-1回答:2

我正在尝试使用python编写一个程序,该程序查看列表中的用户输入数字,如果它们都是偶数,则如果它们都是奇数,则将打印“ all even”或“ all奇数”。混合使用偶数和奇数,然后将显示“非偶数或奇数”。我不知道如何启动它。

python python-3.x list function user-defined-functions
2个回答
0
投票

这是一种简单的方法,您至少应该分享下一次尝试的内容!

test = [[1,2,3,4,5], [2,4,6,8], [1,3,5,7]]
for test in test:
    s = set([x%2 for x in test])
    if len(s) == 2:
        print("Mixed")
    else:
        if list(s)[0] == 0:
            print("even")
        else:
            print("odd")

0
投票
Create a list and a set ( a set holds only unique values, useful for this )
Repeat a few times:
Ask for a number 
Add the number to the list
Add the number to a set with %2 of the number
At the end, check the length of the set, 
if it is two, you have mixed numbers
else if the number is 1, you have Odd Numbers
else you have even numbers

这就是您可以用来编写程序的方式。如果有任何问题,可以在下面查看。学习Python很有趣,这是一种很棒的语言:

c=[]
d=set()
c.append(int(input("Enter the first of 4 numbers: ")))
d.add(c[0]%2)
for x in range(1,4):
  c.append(int(input("Enter the next number: ")))
  d.add(c[x]%2)
if len(d) == 2:
  print("Mixed Numbers in {}".format(c))
elif d.pop() == 1:
  print("Odd Numbers in {}".format(c))
else:
  print("Even Numbers in {}".format(c))

© www.soinside.com 2019 - 2024. All rights reserved.