繁体   English   中英

如何使用列表理解改进以下代码片段

[英]How to improve the below code snippets with list comprehension

我正在尝试使用列表理解将以下代码转换为有效的方式。 我不想在我的代码中使用 While 循环。 这里的问题是两个变量在每个 while 和 for 循环中都会增加。

输入:

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

我的代码片段:

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)

任何人都可以建议如何使用列表理解或任何其他方式来实现上述代码,而无需 while 循环

尝试这个:

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

试试这个方法

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)

获取所有组合并检查它是否在字符串中

代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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