需要在列表内部划分字符串理解

时间:2012-10-01 02:27:53

标签: python

问我:通过过滤下限列表,创建并打印单词的前半部分与单词的后半部分匹配的单词列表。例子包括“bonbon”,“froufrou”,“gaga”和“murmur”。

到目前为止:

[word for word in lowers if list.(word)(1:len(word)/2:)==list.(word)(len(word)/2::)]

我不确定如何使单词成为列表,因此我只能使用某些字符作为此过滤器。我知道这不会起作用,但到目前为止我的逻辑。

2 个答案:

答案 0 :(得分:2)

试试这个:

[word for word in lowers if word[len(word)//2:] == word[:len(word)//2]]

答案 1 :(得分:2)

逻辑错误:您在list.(word)(1:len(word)/2:)

中从索引1而不是0切片

语法错误:list.(word)语法不正确,列表切片使用[] not()。只需使用word[start:stop]即可将其分解

使用:

[word for word in lowers if word[:len(word)//2]==word[len(word)//2:]]

编辑:感谢Ignacio Vazquez-Abrams的评论 - 使用整数除法(//运算符)来兼容Python 3