从列表中删除回文元素的Python程序
给定一个列表,这里的任务是编写Python程序,该程序可以删除列表中所有具有回文等效元素的元素。
例子:
Input : test_list = [54, 67, 12, 45, 98, 76, 9]
Output : [12, 98]
Explanation : 67 has 76 as palindromic element, both are omitted.
Input : test_list = [54, 67, 12, 45, 98, 76, 9, 89]
Output : [12]
Explanation : 98 has 89 as palindromic element, both are omitted.
方法 1:使用str() 、列表推导和int()
在这种情况下,元素首先使用 str() 转换为字符串,使用 int() 反转并重新转换为整数,并检查回文的出现,如果存在,则结果中省略元素及其回文。
例子:
Python3
# initializing list
test_list = [54, 67, 12, 45, 98, 76, 9]
# printing original list
print("The original list is : " + str(test_list))
# reversing and comparing for presence using in operator
res = [ele for ele in test_list if int(str(ele)[::-1]) not in test_list]
# printing result
print("List after palindromic removals ? : " + str(res))
Python3
# initializing list
test_list = [54, 67, 12, 45, 98, 76, 9]
# printing original list
print("The original list is : " + str(test_list))
# reversing and comparing for presence using in operator
res = list(filter(lambda ele: int(str(ele)[::-1]) not in test_list, test_list))
# printing result
print("List after palindromic removals ? : " + str(res))
输出:
The original list is : [54, 67, 12, 45, 98, 76, 9]
List after palindromic removals ? : [12, 98]
方法 2:使用filter() 、 str()和int()
在这里,我们使用 filter() 执行过滤每个元素的任务。 str() 和 int() 用于与上述方法相同的函数。
例子:
蟒蛇3
# initializing list
test_list = [54, 67, 12, 45, 98, 76, 9]
# printing original list
print("The original list is : " + str(test_list))
# reversing and comparing for presence using in operator
res = list(filter(lambda ele: int(str(ele)[::-1]) not in test_list, test_list))
# printing result
print("List after palindromic removals ? : " + str(res))
输出:
The original list is : [54, 67, 12, 45, 98, 76, 9]
List after palindromic removals ? : [12, 98]