简体   繁体   English

如何使用列表理解或切片来测试字符串列表是否为回文?

[英]How to test if a list of strings are palindromes using list comprehension or slicing?

I am trying to test if a list of strings are palindromes using list comprehension or slicing.我正在尝试使用列表理解或切片来测试字符串列表是否是回文。 I converted str1 to list using word_list=str1.split() .我使用word_list=str1.split()str1转换为列表。 However, the palindrome test,然而,回文测试,

word=[w for w in word_list if w[0:9:1]==w[0:9:1][::-1]]

works for only the first word.仅适用于第一个单词。 Since the words have different lengths, I am wondering if there are concise way of writing the code without using common loops?由于单词有不同的长度,我想知道是否有简洁的方法来编写代码而不使用通用循环?

str1='avallava si padre emirime'

@Chris_Rands answer solved the problem. @Chris_Rands答案解决了问题。 word=[w for w in word_list if w==w[::-1]]

The line below iterates through word_list, keeps the words which are palindromes and stores them as a list. 下面的行遍历word_list,保留回文词并将其存储为列表。

palindromes = [w for w in word_list if w == w[::-1]]

If world_list = ['avallava', 'si', 'padre', 'emirime'] , 如果world_list = ['avallava', 'si', 'padre', 'emirime']

then palindromes = ['avallava', 'emirime'] 然后palindromes = ['avallava', 'emirime']

a=['aba','abc','lil','ozx'] b=[] for i in a: if i==i[::-1]: b.append(i) a=['aba','abc','lil','ozx'] b=[] for i in a: if i==i[::-1]: b.append(i)

print(b)打印(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM