在Python中,如何使用list comprehensions下的if和else语句从数字列表中列出奇数和偶数?

2024-04-24 18:54:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一些代码,将偶数和奇数从数字列表中分离出来。你知道吗

我可以使用列表理解下的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]

Tags: the代码from列表if数字语句num
1条回答
网友
1楼 · 发布于 2024-04-24 18:54:35

你不这么做有什么原因吗

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)

相关问题 更多 >