简体   繁体   中英

How to improve the below code snippets with list comprehension

I'm trying to convert the below code into efficient way using list comprehension. I don't want to use While loop in my code. Problem here is two variables are getting incremented every while and for loop.

Input:

string1 = "there is a boy in the lane"

Output:

['there', 'is', 'a', 'boy', 'in', 'the', 'lane', 
 'there is', 'is a', 'a boy', 'boy in', 'in the', 'the lane', 
 'there is a', 'is a boy', 'a boy in', 'boy in the', 'in the lane', 
 'there is a boy', 'is a boy in', 'a boy in the', 'boy in the lane', 
 'there is a boy in', 'is a boy in the', 'a boy in the lane', 
 'there is a boy in the', 'is a boy in the lane', 
 'there is a boy in the lane']

My Code Snippet:

import re  
a = "there is a boy in the lane"   
s = re.split("\s",a)   
f_list = []   
for i in range(0,len(s)):   
  l = 0     
  l1 = i+1      
  while(l<len(s)-i):      
    f_list.append(" ".join(s[l:l1]))     
    l = l+1     
    l1 = l1+1     
print(f_list)

Can anyone suggest how to implement the above code using list comprehension or any other way without while loop

Try this:

a = "there is a boy in the lane"
s = a.split(' ')
f_list = [' '.join(s[j: j+i]) for i in range(1, len(s) + 1) for j in range(len(s) - i + 1)]
print(f_list)

Output:

['there', 'is', 'a', 'boy', 'in', 'the', 'lane', 'there is', 'is a', 'a boy', 'boy in', 'in the', 'the lane', 'there is a', 'is a boy', 'a boy in', 'boy in the', 'in the lane', 'there is a boy', 'is a boy in', 'a boy in the', 'boy in the lane', 'there is a boy in', 'is a boy in the', 'a boy in the lane', 'there is a boy in the', 'is a boy in the lane', 'there is a boy in the lane']

Try this approach

from itertools import combinations

string1 = "there is a boy in the lane"
list1 = string1.split()
combo = [' '.join(com) for i in range(1, len(list1) + 1) for com in combinations(list1, i)]
print(combo)

Get all combinations and check if it is in the string

Code:

import itertools

string1 = "there is a boy in the lane"
l_str = string1.split()

result = [' '.join(s) for i in range(1, len(l_str)+1) for s in itertools.combinations(l_str, r=i) if string1.find(' '.join(s)) >= 0]
print(result)

Output:

['there', 'is', 'a', 'boy', 'in', 'the', 'lane', 'there is', 'is a', 'a boy', 'boy in', 'in the', 'the lane', 'there is a', 'is a boy', 'a boy in', 'boy in the', 'in the lane', 'there is a boy', 'is a boy in', 'a boy in the', 'boy in the lane', 'there is a boy in', 'is a boy in the', 'a boy in the lane', 'there is a boy in the', 'is a boy in the lane', 'there is a boy in the lane']                   

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