您的位置:

Python 程序:去除列表中偶数

编写一个 Python 程序,使用 for 循环从给定列表中删除偶数。if 语句检查列表项是否可被 2 整除。如果为真,则使用列表删除功能删除该列表项。

# Remove Even List Items

evenList = [11, 22, 31, 44, 51, 65, 71, 82, 91]
print("List Items = ", evenList)

for ev in evenList:
    if (ev % 2 == 0):
        evenList.remove(ev)

print("List Items after removing even Items = ", evenList)

使用 While 循环删除列表中偶数的 Python 程序

# Remove Even index List Items

evenList = []

listNumber = int(input("Enter the Total List Items = "))
for i in range(1, listNumber + 1):
    listValue = int(input("Enter the %d List Item = " %i))
    evenList.append(listValue)

print("List Items = ", evenList)
i = 0

while (i < len(evenList)):
    if (evenList[i] % 2 == 0):
        evenList.remove(evenList[i])
    i = i + 1

print("List Items after removing even Items = ", evenList)

Python 使用 while 循环输出 从列表中删除偶数

Enter the Total List Items = 6
Enter the 1 List Item = 21
Enter the 2 List Item = 98
Enter the 3 List Item = 7
Enter the 4 List Item = 32
Enter the 5 List Item = 19
Enter the 6 List Item = 32
List Items =  [21, 98, 7, 32, 19, 32]
List Items after removing even Items =  [21, 7, 19]

在这个 Python 例子中,我们使用列表理解从给定列表中移除或删除偶数。

# Remove Even index List Items

evenList = []

listNumber = int(input("Enter the Total List Items = "))
for i in range(1, listNumber + 1):
    listValue = int(input("Enter the %d List Item = " %i))
    evenList.append(listValue)

print("List Items = ", evenList)

evenList = [ev for ev in evenList if ev % 2 != 0]    
print("List Items after removing even Items = ", evenList)

使用列表理解输出从列表中删除偶数

Enter the Total List Items = 3
Enter the 1 List Item = 11
Enter the 2 List Item = 22
Enter the 3 List Item = 33
List Items =  [11, 22, 33]
List Items after removing even Items =  [11, 33]

这个 Python 程序使用了列表、过滤器和 l ambda 函数来移除偶数。

# Remove Even index List Items

evenList = []

listNumber = int(input("Enter the Total List Items = "))
for i in range(1, listNumber + 1):
    listValue = int(input("Enter the %d List Item = " %i))
    evenList.append(listValue)

print("List Items = ", evenList)

oddList = list(filter(lambda x : (x % 2 != 0), evenList))    
print("List Items after removing even Items = ", oddList)

删除列表偶数输出

Enter the Total List Items = 4
Enter the 1 List Item = 21
Enter the 2 List Item = 42
Enter the 3 List Item = 99
Enter the 4 List Item = 56
List Items =  [21, 42, 99, 56]
List Items after removing even Items =  [21, 99]