为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

海绵宝宝撒 2021-10-12 16:49:08
我有一个项目清单:例如: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',]
查看完整描述

3 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

您可以迭代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']


查看完整回答
反对 回复 2021-10-12
?
呼唤远方

TA贡献1856条经验 获得超11个赞

只需关闭您提供的信息,您就可以做到这一点。


    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 s

Press any key to continue . . .


查看完整回答
反对 回复 2021-10-12
?
长风秋雁

TA贡献1757条经验 获得超7个赞

干得好:


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_list


a = ['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']



查看完整回答
反对 回复 2021-10-12
  • 3 回答
  • 0 关注
  • 177 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号