python - 按条件连接列表中的字符串
问题描述
我有这个字符串列表:
listInfos = ['D D R: 17/10/2018', 'nothing past this date', 'D D R: 4/10/2018', 'D D R: 2/10/2018']
我想对其进行排序,结果将是:
parsedList = ['D D R: 17/10/2018 & nothing past this date', 'D D R: 4/10/2018', 'D D R: 2/10/2018']
a 之后的每个元素'D D R ..'
都应该与它相关联,直到我们有一个新的 'D D R ..'
有没有快速的命令来做这样的事情?我已经尝试过了,但它不起作用。
parsedList = []
for i in range(len(listeInfos)):
tmpList = []
if re.match(r'^D D R', listeInfos[i]):
tmpList.append(listeInfos[i])
while not(re.match(r'^D D R', listeInfos[i+1])):
tmpList.append(listeInfos[i])
i += 1
else:
parsedList.append(tmpList)
break
break
i = j
谢谢!
解决方案
问题:“DDR ..”之后的每个元素都应该与之关联,直到我们有一个新的“DDR ..”
不要与 Indizies 战斗!例如:
注意:
listInfos
必须以'DD R'开头!
listInfos = ['D D R: 17/10/2018', 'nothing past this date', 'D D R: 4/10/2018', 'D D R: 2/10/2018']
parsedList = []
# Loop the List of Strings
for s in listInfos:
# Condition not
if not s.startswith('D D R'):
# if True concat 's' with the last String in the List
parsedList[-1] += " " + s
else:
# Append 's' as a new String to the List
parsedList.append(s)
for s in parsedList:
print(s)
输出:
D D R: 17/10/2018 nothing past this date D D R: 4/10/2018 D D R: 2/10/2018`
用 Python 测试:3.5.3
推荐阅读
- java - 带有逗号分隔列表的正向 Lookbehind
- ruby-on-rails - nginx是否支持早期提示请求(103状态)
- javascript - 闭包和计数器堆叠
- c# - ASP.NET C# 从访问数据库中删除
- android - 如何在单个活动中加载多个 AndroidViewModel 以访问使用 Room 从多个表返回值的 LiveData
- java - 为什么这里没有显示图像?
- bash - 真正的 bash 行数
- ruby-on-rails - Docker nginx 和应用程序正在运行,但应用程序未在浏览器上显示
- c# - OGR shapefile 点示例 C#
- javascript - 使用函数动态填充下拉列表