python - 如何使用列表理解改进以下代码片段
问题描述
我正在尝试使用列表理解将以下代码转换为有效的方式。我不想在我的代码中使用 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 循环
解决方案
尝试这个:
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']
推荐阅读
- javascript - 将数组分配为地图中的对象值
- html - 打开纸张下拉菜单时滚动网页
- android - 命名功能模块包
- android-layout - TabLayout 示例显示带有 xml 布局的选项卡,没有片段
- amazon-web-services - 无法以编程方式调用 AWS lambda
- ruby-on-rails - puma.access.log 中的“日志写入失败。死锁;递归锁定”
- npm - 无法在 ubuntu 18.04 中安装 npm,E:无法纠正问题,您持有损坏的软件包
- vb.net - vb.NET中的字符位置范围
- python - mathplotlib.dates.DateFormatter() 是否已弃用,因为 strftime() 是?
- mysql - 使用随机值作为主键时的 InnoDB 聚集索引性能