как соединить элемент с другим в том же списке на основе условия - PullRequest
0 голосов
/ 16 января 2019

У меня есть список предметов: например:

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',]

Ответы [ 3 ]

0 голосов
/ 16 января 2019

Просто уйдя от предоставленной вами информации, вы можете сделать это.

    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 . . .
0 голосов
/ 16 января 2019

Вот, пожалуйста:

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']
0 голосов
/ 16 января 2019

Вы можете перебрать 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']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...