在一个lambda函数中转换两个for循环方法

问题描述 投票:1回答:2

我创建了这个'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])
  • w1,w2
  • 1,p
  • w1,w4
  • ....
  • ....
  • A,和
  • w2,w4
  • ....

但我想在lambda函数格式中使用是在我的apache spark程序中。有人能帮我吗?

提前致谢

python function lambda
2个回答
5
投票

我将从直接遍历列表开始:

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))

1
投票

使用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')
© www.soinside.com 2019 - 2024. All rights reserved.