在一个lambda函数中变换两个循环的方法

2024-09-24 06:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了这个“two 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
  • w1和w3
  • w1和w4
  • 。。。。你知道吗
  • 。。。。你知道吗
  • w2、w3
  • w2、w4
  • 。。。。你知道吗

但是我想要lambda函数格式,以便在我的apachespark程序中使用。有人能帮我吗?你知道吗

提前谢谢


Tags: 方法in标记列表forlenrange句子
2条回答

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

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

相关问题 更多 >