我有以下代码行:
val = tuple(s for s in name_list if str(ngram) in s)
这将搜索列表“name_list”并打印列表中包含子字符串“ngram”的所有元素。 Python 似乎具有这种强大的“if in”魔力,而且它非常紧凑。
我习惯于将循环和条件视为:
for line in file:
和
if x == y:
那么有人可以解释一下这些衬里的实际结构吗?
我问的原因是因为在我的特定情况下,列表“name_list”是 60K+ 元素的列表。我想在找到十个子字符串后立即返回并退出我的函数。更具体地说:
s
for s in name_list:
if str(ngram) in s:
if len(s) <= 10:
return true
它前面的变量 s 单独存在让我不知道如何引用它,如果 s 只是我的一个子字符串匹配。或附加到每个找到的子字符串的列表,然后我将其转换为元组。
我需要一些认真的心理帮助。
请您参考如下方法:
要切割任意可迭代对象(包括生成器),请使用函数 itertools.islice :
gen = (s for s in name_list if str(ngram) in s) # this is a generator
val = tuple(itertools.islice(gen, 10)) # take only 10 first elements
关于生成器表达式的更多信息 in this question .
为了解决您对阅读整个序列的担忧,这里有一个例子:
def gen():
for x in xrange(1000000): # a lot
print 'Yielding', x # to demo the side effect
yield x
然后 list(itertools.islice(gen(), 3)) 将返回 [0, 1, 2] 和 打印:
Yielding 1
Yielding 2
Yielding 3
然后生成器将停止,因为没有人要求它继续。那叫lazy evaluation (顺便说一句,这篇文章使用 islice 和其他 itertools 的示例对其进行了准确解释)。
