我创建了这个'for for loops'方法,其中假设我将一个句子标记为列表为[w1,w2,w3,..,wn]我想输出以下几个(不是bigrams)
for i in range(len(words)):
for j in range(i+1, range(len(words))):
couples = (words[i], words[j])
但我想在lambda函数格式中使用是在我的apache spark程序中。有人能帮我吗?
提前致谢
我将从直接遍历列表开始:
for x in words:
for y in words:
couples = x, y
然而,这给出了完整的笛卡尔积,这与你原来的不完全相同。所以我们需要第一个循环的索引,但不需要第二个循环:
for i, x in enumerate(words):
for y in words[i:]:
couples = x, y
现在我们可以将它转换为生成器表达式(而不是lambda):
all_couples = ((x, y) for y in words[i:] for i, x in enumerate(words))
使用itertools中的组合将获得您想要的结果。
from itertools import combinations
for tup in combinations(words, 2):
print(tup)
('This', 'is')
('This', 'an')
('This', 'example')
('This', 'sentence')
('is', 'an')
('is', 'example')
('is', 'sentence')
('an', 'example')
('an', 'sentence')
('example', 'sentence')