Home > OS >  Merge every certain number of items in a list
Merge every certain number of items in a list

Time:08-19

I have a list like this

items= ['e', '4', 'e', 'e', '4', '5', '4', '8', 'a', '8', '6', 'd', '8', 'a', 'e', '1', 'b', '6', '2', '1', '6', 'a', 'a', 'a', '2', 'b', 'd', '6', '7', '7', '9', '2']

I want to edit the list so that every 4 items in the list get merged like this

items=['e4ee', '4548', 'a86d', '8ae1', 'b621', '6aaa', '2bd6', '7792']

Edit: My mistake for wording. By not creating a new list I meant by putting the arranged elements into a separate list like this

items = ['e', '4', 'e', 'e', ...

items2 = ['e4ee', '4548', ... 

CodePudding user response:

You could do it like this although this does create a new list:

items = ['e', '4', 'e', 'e', '4', '5', '4', '8', 'a', '8', '6', 'd', '8', 'a', 'e', '1', 'b', '6', '2', '1', '6', 'a', 'a', 'a', '2', 'b', 'd', '6', '7', '7', '9', '2']

items = [''.join(items[i:i 4]) for i in range(0, len(items), 4)]

print(items)

Output:

['e4ee', '4548', 'a86d', '8ae1', 'b621', '6aaa', '2bd6', '7792']

CodePudding user response:

If you absolutely do not want to create a new list (as stated):

result_len = len(items) // 4
for i in range(result_len):
    j = (i*4)
    items[i] = ''.join(items[j:(j 4)])
for i in range(len(items) - 1, result_len - 1, -1):
    del items[i]

Does exactly len(items) iterations and never creates a new list.

The first loop updates the first result_len items in the list to the desired values. The second one deletes the rest of the items from it.

EDIT: Whoops, had a bug there. Now it should be correct.

  • Related