简体   繁体   中英

One liner - Nested for loop

Trying to avoid nested for loops but I'm unsure how I shall use words = x.split() and words[y:y+n] inside the one liner.

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

So far I'm working with the following:

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

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

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

n is never changed so always 1

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

so simplify that

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

which is basically

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

which get us to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM