如何使用Python中列表理解下的if和else语句从数字列表中列出奇数和偶数?

时间:2019-07-04 15:16:05

标签: python python-3.x

我正在编写一些代码,以将偶数和奇数与数字列表分开。

我可以使用列表理解下的if语句从列表中提取偶数,但是我不知道如何使用列表理解下的else语句并获得奇数列表输出。

代码:

evenList = [num for num in range (0,11) if num%2==0]
print(f'Even numbers from the list are {evenList}')

所需的输出:

Even numbers from the list are [2, 4, 6, 8, 10]
Odd numbers from the list are [1, 3, 5, 7, 9]

1 个答案:

答案 0 :(得分:1)

您是否有理由不这样做?

evenList = [num for num in range (0,11) if num%2==0]
print('Even numbers from the list are ', end='')
print(evenList)

oddList = [num for num in range (0,11) if num%2==1]
print('Even numbers from the list are ', end='')
print(oddList)

编辑:如果您只想遍历列表,则可以执行以下操作:

evenList = []
oddList = []

for num in range (0,11):
    if num % 2 == 0:
        evenList.append(num)
    else:
        oddList.append(num)

print(evenList)
print(oddList)