Home > Mobile >  How to merge every three (or more) elements of list in one in python?
How to merge every three (or more) elements of list in one in python?

Time:10-05

list = [1, 'one', 'first', 2, 'two', 'second', 3, 'three', 'third', 4, 'four', 'fourth', 5, 'five', 'fifth', 6, 'six', 'sixth']

is it compact way to make new list like this? (merging 3 elements, then another 3...):

['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fivefifth', '6sixsixth']

CodePudding user response:

Using a list comprehension with conversion to string and join:

N = 3
out = [''.join(map(str, lst[i:i N])) for i in range(0, len(lst), N)]

Output:

['1onefirst',
 '2twosecond',
 '3threethird',
 '4fourfourth',
 '5fivefifth',
 '6sixsixth']

CodePudding user response:

You may want to use a combination of list comprehensions and slices for this purpose in Python:

# Defining the input list
input_list = [
    1, "one", "first",
    2, "two", "second",
    3, "three", "third",
    4, "four", "fourth",
    5, "five", "fifth",
    6, "six", "sixth"
]

# Using slices of the input in a list comprehension
list_merge_every_third = [
    ''.join(str(e) for e in input_list[i * 3 : i * 3   3])
    for i in range(len(input_list) // 3)
]

Note: You may first want to test if your input list length is a multiple of 3.

I also suggest not using the symbol "list" to designate your input, because it is a reserved keyword of the Python language to designate the list type.

CodePudding user response:

I hope the following solution is what you are looking for.

    list = [1, "one", "first", 2, "two", "second", 3, "three", "third",
    4, "four", "fourth", 5, "five", "fifth", 6, "six", "sixth"]

    def merge_list(list, n):
        temp_list = [list[i:i   n] for i in range(0, len(list), n)]
        return [''. join(str(i) for i in temp_list) for temp_list in temp_list]

   list_merge_every_third = merge_list(list, 3)
   print(list_merge_every_third)

The resulting list looks like this:

['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fivefifth', '6sixsixth']

CodePudding user response:

You could also use a generator to return the combined triplets like this:

input_list = [
    1, "one", "first",
    2, "two", "second",
    3, "three", "third",
    4, "four", "fourth",
    5, "five", "fifth",
    6, "six", "sixth"
]

def triples(_list):
    for i in range(0, len(_list), 3):
        yield ''.join(map(str, _list[i:i 3]))

print([triple for triple in triples(input_list)])

Output:

['1onefirst', '2twosecond', '3threethird', '4fourfourth', '5fivefifth', '6sixsixth']
  • Related