亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何根據條件將元素連接到同一列表中的其他元素

如何根據條件將元素連接到同一列表中的其他元素

海綿寶寶撒 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 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號