首页 > 解决方案 > 按条件连接列表中的字符串

问题描述

我有这个字符串列表

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

谢谢!

标签: pythonlist

解决方案


问题:“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


推荐阅读