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]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP