Python 程序以两个不同的列表分割偶数和奇数组成。


在本程序中,我们创建一个用户输入列表,且这些元素是奇数和偶数元素的混合体。我们的任务是将这些列表分成两个列表。一个包含奇数元素,另一个包含偶数元素。

示例

Input: [1, 2, 3, 4, 5, 9, 8, 6]
Output
Even lists: [2, 4, 8, 6]
Odd lists: [1, 3, 5, 9]

算法

Step 1 : create a user input list.
Step 2 : take two empty list one for odd and another for even.
Step 3 : then traverse each element in the main list.
Step 4 : every element is divided by 2, if remainder is 0 then it’s even number and add to the even list, otherwise its odd number and add to the odd list.

示例代码

# Python code to split into even and odd lists 
# Funtion to split 
def splitevenodd(A): 
   evenlist = [] 
   oddlist = [] 
   for i in A: 
      if (i % 2 == 0): 
         evenlist.append(i) 
      else: 
         oddlist.append(i) 
   print("Even lists:", evenlist) 
   print("Odd lists:", oddlist) 
  
# Driver Code 
A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First  List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
splitevenodd(A) 

输出

Enter the size of the First List :: 8
Enter the Element of First  List ::
1
2
3
4
5
9
8
6
Even lists: [2, 4, 8, 6]
Odd lists: [1, 3, 5, 9]

更新时间:2019-07-30

22K+ 浏览量

开启您的职业生涯

完成课程并获得认证

立即开始
广告