Python - 测试列表是否为回文
给定一个列表,检查它是否是回文。
Input : test_list = [4, 5, 4]
Output : True
Explanation : List is same from front and rear.
Input : test_list = [4, 5, 5]
Output : True
Explanation : List is not same from front and rear.
方法#1:使用列表切片
在此,我们首先提取并反转列表的第二半,然后比较是否相等,如果发现相等,则我们得出其回文。
Python3
# Python3 code to demonstrate working of
# Test if list is Palindrome
# Using list slicing
# initializing list
test_list = [1, 4, 5, 4, 1]
# printing original list
print("The original list is : " + str(test_list))
# Reversing the list
reverse = test_list[::-1]
# checking if palindrome
res = test_list == reverse
# printing result
print("Is list Palindrome : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test if list is Palindrome
# Using reversed()
# initializing list
test_list = [1, 4, 5, 4, 1]
# printing original list
print("The original list is : " + str(test_list))
# reversing list
rev_list = list(reversed(test_list))
# checking for Palindrome
res = rev_list == test_list
# printing result
print("Is list Palindrome : " + str(res))
输出
The original list is : [1, 4, 5, 4, 1]
Is list Palindrome : True
方法#2:使用reversed()
在这种情况下,我们简单地反转列表并检查原始列表和反转列表是否相似。
蟒蛇3
# Python3 code to demonstrate working of
# Test if list is Palindrome
# Using reversed()
# initializing list
test_list = [1, 4, 5, 4, 1]
# printing original list
print("The original list is : " + str(test_list))
# reversing list
rev_list = list(reversed(test_list))
# checking for Palindrome
res = rev_list == test_list
# printing result
print("Is list Palindrome : " + str(res))
输出
The original list is : [1, 4, 5, 4, 1]
Is list Palindrome : True