Merge some list items in a Python List

后端 未结 5 2061
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 01:42

Say I have a list like this:

[a, b, c, d, e, f, g]

How do modify that list so that it looks like this?

[a, b, c, def, g]
         


        
5条回答
  •  时光取名叫无心
    2020-12-24 01:59

    Of course @Stephan202 has given a really nice answer. I am providing an alternative.

    def compressx(min_index = 3, max_index = 6, x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']):
        x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
        return x
    compressx()
    
    >>>['a', 'b', 'c', 'def', 'g']
    

    You can also do the following.

    x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
    print(x)
    
    >>>['a', 'b', 'c', 'def', 'g']
    

提交回复
热议问题