如何根据条件将元素连接到同一列表中的其他元素

我有一个项目清单:例如:

a = ['when', '#i am here','#go and get it', '#life is hell', 'who', '#i am here','#go and get it',]

我想根据条件合并列表项,即合并所有项目,直到该项目在第一个位置具有 # 并将其替换为 when 或 who。我想要的输出是:

['when', 'when i am here','when go and get it', 'when life is hell', 'who', 'who i am here','who go and get it',]


海绵宝宝撒
浏览 178回答 3
3回答

桃花长相依

您可以迭代a,如果单词不是以 开头,则保存该单词,如果是'#',则替换'#'为保存的单词:for i, s in enumerate(a):    if s.startswith('#'):        a[i] = p + s[1:]    else:        p = s + ' 'a 变成:['when', 'when i am here', 'when go and get it', 'when life is hell', 'who', 'who i am here', 'who go and get it']

呼唤远方

只需关闭您提供的信息,您就可以做到这一点。    a = ['when', '#i am here','#go and get it', '#life is hell', 'who', '#i am here','#go and get it']    whoWhen = ""                                                 #are we adding 'who or when'    output = []                                                  #new list    for i in a:                                                  #loop through        if " " not in i:                                         #if there's only 1 word            whoWhen = i + " "                                    #specify we will use that word            output.append(i.upper())                             #put it in the list        else:                                       output.append(i.replace("#", whoWhen))               #replace hashtag with word    print(output)印刷:['WHEN', 'when i am here', 'when go and get it', 'when life is hell', 'WHO', 'who i am here', 'who go and get it']Process returned 0 (0x0)        execution time : 0.062 sPress any key to continue . . .

长风秋雁

干得好:def carry_concat(string_list):    replacement = ""  # current replacement string ("when" or "who" or whatever)    replaced_list = []  # the new list    for value in string_list:        if value[0] == "#":            # add string with replacement            replaced_list.append(replacement + " " + value[1:])        else:            # set this string as the future replacement value            replacement = value            # add string without replacement            replaced_list.append(value)    return replaced_lista = ['when', '#i am here','#go and get it', '#life is hell', 'who', '#i am here','#go and get it',]print(a)print(carry_concat(a))这打印:['when', '#i am here', '#go and get it', '#life is hell', 'who', '#i am here', '#go and get it']['when', 'when i am here', 'when go and get it', 'when life is hell', 'who', 'who i am here', 'who go and get it']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python