首页 > 解决方案 > 如何使用列表理解改进以下代码片段

问题描述

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

输入 :

string1 = "there is a boy in the lane"

输出:

['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 循环

标签: pythonpython-3.xlist-comprehension

解决方案


尝试这个:

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)

输出:

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

推荐阅读