python - Python:将列表切成子列表,每次元素都以特定的子字符串开头
问题描述
我想将列表切成子列表,每次元素都以特定的子字符串开头。
所以说我有:
a = ['XYthe', 'cat' , 'went', 'XYto', 'sleep','XYtoday','ok']
b = 'XY'
并想返回:
a1 = ['XYthe', 'cat', 'went']
a2 = ['XYto', 'sleep']
a3 = ['XYtoday', 'ok']
谁能帮忙?谢谢!
解决方案
a = ['XYthe', 'cat' , 'went', 'XYto', 'sleep','XYtoday','ok']
b = 'XY'
final_list = []
for word in a:
if word.startswith(b): # if the word starts with 'XY'...
final_list.append([word]) # ...then make a new sublist
else:
final_list[-1].append(word) # otherwise, add the word to the last sublist so far
print(final_list)
# [['XYthe', 'cat', 'went'], ['XYto', 'sleep'], ['XYtoday', 'ok']]
如果 的第一个元素a
不包含b
,代码将引发IndexError
. 这是有意的 - 您可以使用它来验证它a
并且b
是此代码片段的有效输入。
推荐阅读
- html - 如何垂直降低视频html
- javascript - 跨多个浏览器窗口/选项卡刷新 JWT 一次
- r - 使用正则表达式提取名称和数字
- java - 在图像中查找迷宫走廊的大小
- python - 如何将圆形图像裁剪为内切正方形,然后裁剪为内切圆,最后裁剪为内切正方形?
- php - Wordpress - PHP 调用带有查询的 Google 表格单元格?
- bash - 无法通过 shellscript 激活 virtualenv
- django - Django Rest Framework - 具有嵌套外键的模型关系
- ruby-on-rails - 如何访问远程 VM 中的 Rails 服务器
- android - PWA 有没有办法访问主机设备的电话号码?