[英]Using list comprehension and sets
创建并打印满足以下条件的单词列表:
例如,单词“ballooned”应该包含在你的列表中,因为由奇数字母“blond”形成的单词和由偶数字母“aloe”形成的单词都在小写单词。 类似地,“三年”分裂为“轻微”和“肾脏”,两者都在单词列表中。
我的老师告诉我们,我们应该使用一套: s=set(lowers)
因为这会更快。
到目前为止我有什么:
s=set(lowers)
[word for word in lowers if len(word)>=8
and list(word)(::2) in s
and list(word)(::-2) in s]
我认为我没有使用正确的设置。 有人可以帮助我让这个工作
问题是你将word
转换为列表(不必要),你的切片不在括号中(你使用括号),你的第二个切片使用错误的索引(应该是1::2
,而不是::-2
)。
以下是正确完成的切片:
>>> word = "ballooned"
>>> word[::2]
'blond'
>>> word[1::2]
'aloe'
请注意, s
是小写单词集合的奇数名称。 一个更好的名字是words
。
你对set
使用是正确的。 你的老师希望你使用一组的原因是它的速度要快得多一组比它是一个列表的成员测试。
把它放在一起:
words = set(lowers)
[word for word in words if len(word) >= 8
and word[::2] in words
and word[1::2] in words]
以下是如何在列表理解中构建条件检查的快速示例:
>>> word = 'ballooned'
>>> lowers = ['blond', 'aloe']
>>> s = set(lowers)
>>> len(word) >= 8 and word[::2] in s and word[1::2] in s
True
编辑:刚才意识到lowers
包含有效单词和“搜索”单词,如'ballooned'和'triennially',无论如何你应该能够在列表理解中使用上述条件来获得正确的结果。
list(word)(::2)
首先,访问索引范围的语法是使用平方括号,同样,您不需要先将word
转换为列表,您可以直接在字符串上执行此操作:
>>> 'ballooned'[::2]
'blond'
另外, [::-2]
不会给你不均匀的单词,而是另一个单词的反转版本。 你需要使用[1::2]
(即跳过第一个,然后是第二个字符):
>>> 'ballooned'[::-2]
'dnolb'
>>> 'ballooned'[1::2]
'aloe'
一般来说,分别测试某些部件以确定它们是否真的按照您的想法行事总是一个好主意。
这应该这样做:
s=set(lowers)
[word for word in lowers if len(word)>=8 and word[::2] in s and word[1::2] in s]
或使用all()
:
In [166]: [word for word in lowers if all((len(word)>=8,
word[::2] in s,
word[1::2] in s))]
使用[::]
not (::)
并且这里不需要list()
,加上用于放置在奇数位置的字母形成的单词使用[1::2]
。
In [151]: "ballooned"[::2]
Out[151]: 'blond'
In [152]: "ballooned"[1::2]
Out[152]: 'aloe'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.