我正在写一些代码,将偶数和奇数从数字列表中分离出来。你知道吗
我可以使用列表理解下的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]
你不这么做有什么原因吗
编辑:如果您只想遍历列表一次,可以执行以下操作:
相关问题 更多 >
编程相关推荐