简体   繁体   中英

merging strings from a list in python

I tried to define a function on python to merge the strings on a given index range, from a list of strings. Here is my code:

def merge_some(L,i,j):
    result=L[:]
    merging=''
    for k in range(i,j+1):
        merging +=L[k]
    result[i:j+1]=merging
    return result

trial= ['a','b','c','d','e','f']
print(merge_some(trial, 1,3))  #index 3 included

The output should be:

['a','bcd','d','e','f']

The code should work fine, but if I run it, I just get back the original list, which is quite strange to me. Whilst I know there's plenty of methods to compute such function (eg using the.join() method instead of looping), I would like to ask if somebody has any idea of the cause of such weird behaviour. Any idea would be very much appreciated. Many thanks!

str.join() should fox this for you:

def merge_some(l, from_i,to):
    return l[: from_i]+[''.join(l[from_i:to+1])]+l[to+1:]

trial= ['a','b','c','d','e','f']
print(merge_some(trial, 1,3))
>>> ['a','bcd','e','f']

Note: you miscalculated the indexes when suggesting the expected result (therefore you added j+1, which to my eyes seems not very intuitive), but in case you meant that you want many items and not 'to' just do:

def merge_some(l, from_i,many):
    return l[: from_i]+[''.join(l[from_i: from_i + many -1])]+l[from_i +many-1:]
trial= ['a','b','c','d','e','f']
print(merge_some(trial, 1,3))
>>> ['a','bcd','e','f']

You can do something like this:

def merge_some(L,i,j):
    result=L[:]
    result[i:j+1]=[''.join(L[i:j+1])]
    return result


>>> merge_some(['a','b','c','d','e','f'], 1,3)
['a', 'bcd', 'e', 'f']

There are two things to note:

  1. The part result[i:j+1] is a slice assignment that replaces the contents of the slice with the contents of the RH side (even if a different size than the slice);
  2. The ''.join(L[i:j+1]) creates a single string from those elements;
  3. The [...] around [''.join(L[i:j+1])] makes that string act as a single element for the slice assignment.

First of all, many thanks to everybody for your help. While I knew already the.join() method, as mentioned in my question, I just spotted what was missing in my code and the reason of that strange behaviour:

def merge_some(L,i,j):
    try:
        result=L[:]
        merging=''
        for k in range(i,j+1):
            merging +=L[k]
        result[i:j+1]=[merging]
        return result
    except:
        return []

trial= ['a','b','c','d','e','f']
print(merge_some(trial, 1,3))   #The index=3 is also merged in the script

Therefore what was missing is [merging] , ie slice assignment has to be declared as an iterable.

The way you use the parameter j goes against common practice. It would be more intuitive to not add one to j and instead pass 1 to 4 as arguments when calling merge_some .

The result you get in your question is due to line 6.

The other issue with the code in your question and your answer is that when you pass an empty list you go out of bounds, so you have to add a check for that.

I would suggest the following solution as it also works with empty lists:

def merge_some(values, start, end):
    return list(filter(None, values[:start] + [''.join(values[start:end])] + values[end:]))

letters = ['a', 'b', 'c', 'd', 'e', 'f']
print(merge_some(letters, 1, 4))

Note that I am passing 1 to 4 as parameters.

Result:

>>> ['a', 'bcd', 'e', 'f']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM