[英]How to list out odd and even numbers from a list of numbers using if and else statement under list comprehensions in 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]
您是否有理由不這樣做:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.