一个衬里-嵌套循环

时间:2019-04-03 10:52:19

标签: python for-loop nested

试图避免嵌套的for循环,但是我不确定如何在一个衬里使用words = x.split()words[y:y+n]

n = 1
for x in data:
    words = x.split()
    for y in range(len(words)-n+1):
        print(words[y:y+n])

到目前为止,我正在处理以下内容:

data = ' '.join([(x, y) for x in data words = x.split() for y in range(len(words)-n+1) words[y:y+n]])

2 个答案:

答案 0 :(得分:1)

分配临时变量的一种解决方法是改为遍历1个元组:

data = ' '.join(words[y:y+n] for x in data for words in (x.split(),) for y in range(len(words)-n+1))

答案 1 :(得分:0)

n = 1
for x in data:
    words = x.split()
    for y in range(len(words)-n+1):
        print(words[y:y+n])

n永远不会改变,所以总是1

for x in data:
    words = x.split()
    for y in range(len(words)-1+1):
        print(words[y:y+1])

因此简化

for x in data:
    words = x.split()
    for y in range(len(words)):
        print(words[y])

基本上是

for x in data:
    for word in x.split():
        print(word)

这使我们进入

data=' '.join(word for x in data for word in x.split())