Home > Net >  is there an option to combine two itemes in a list python?
is there an option to combine two itemes in a list python?

Time:11-20

i have a list of strings for example: '''list1= ['one','two','three',four','two','five']''' the outpuI i want: '''list1=['one','two-three',four','two-five']''' I want to combine every time the value 'two' apperas with the next value after him

CodePudding user response:

You could use a comprehension over an iterator:

i = iter(list1)
[f"{x}-{next(i)}" if x == "two" else x for x in i]
# ['one', 'two-three', 'four', 'two-five']

Or, if you like it loopy:

res = []
for x in list1:
    if res and res[-1] == "two":
        res[-1]  = "-"   x
    else:
        res.append(x)

CodePudding user response:

The easiest way to do it is to create a new variable. Then loop through the list and whenever you encounter the word "Two" you merge with next word in list

list1= ['one','two','three','four','two','five']

temp = []
n = len(list1)
i = 0
while i < n:
    if list1[i]=="two" and i<n-1:
        temp.append(list1[i] list1[i 1])
        i =2
    else:
        temp.append(list1[i])
        i =1
print(temp)

Result: ['one', 'twothree', 'four', 'twofive']

  • Related