【问题标题】:How to list out odd and even numbers from a list of numbers using if and else statement under list comprehensions in Python?如何在 Python 的列表推导下使用 if 和 else 语句从数字列表中列出奇数和偶数?
【发布时间】:2019-07-04 15:16:05
【问题描述】:

我正在编写一些代码来从数字列表中分离偶数和奇数。

我可以在列表推导下使用 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]

【问题讨论】:

  • 你的意思是像oddList = [num for num in range (0,11) if num%2!=0]?
  • "我不知道如何在列表理解下使用 else 语句并获得奇数列表输出。" 听起来像 xy problem。首先有什么理由这样做吗?
  • 你不需要else,你需要反转你的条件。

标签: python python-3.x


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    相关资源
    最近更新 更多