Home > Software design >  Repeat items in list and maintain order of occurrence until maximum length of list is reached
Repeat items in list and maintain order of occurrence until maximum length of list is reached

Time:10-31

I have a list of values in a list. The length of the list is variable from 1-5. If the list is less than the maximum_length then the list should be expanded, but should never exceed the max length.

I want to expand the list incrementally to distribute the items across the list starting from the first item. Below is the input list and the desired output. The amount of items duplicated is correct, but the order is not.

This list can be string values, so simply sorting the list is not a solution.

Example 1

current_list: ['#f8f8f8']
result: ['#f8f8f8', '#f8f8f8', '#f8f8f8', '#f8f8f8', '#f8f8f8']
desired result: ['#f8f8f8', '#f8f8f8', '#f8f8f8', '#f8f8f8', '#f8f8f8']

Example 2

current_list: ['#090909', '#171717']
result: ['#090909', '#171717', '#090909', '#171717', '#090909']
desired result: ['#090909', '#090909', '#090909', '#171717', '#171717']

Example 3

current_list: ['#d8d8d8', '#ececec', '#f1f1f1']
result: ['#d8d8d8', '#ececec', '#f1f1f1', '#d8d8d8', '#ececec']
desired result: ['#d8d8d8', '#d8d8d8', '#ececec', '#ececec', '#f1f1f1'] 

Example 4

current_list: ['#ecede7', '#eff0eb', '#f1f2ed', '#ffffff']
result: ['#ecede7', '#eff0eb', '#f1f2ed', '#ffffff', '#ecede7']
desired result: ['#ecede7', '#ecede7', '#eff0eb', '#f1f2ed', '#ffffff']

Below is my code to produce the list. How can I update this to get the desired output?

print([current_list * max_len][0][:max_len])

Updated to show that using sort isn't what I need. The purpose of this question is to maintain the distribution of the original list.

CodePudding user response:

Use sort as explained in the comments and to maintain the distribution of the original list, the sort key should be the index of the element in your original list.

max_len = 5
current_list = ['1','2','3','4']
inter = [current_list * max_len][0][:max_len]  # assume we stick with your function
# ['1', '2', '3', '4', '1']
sorted(inter, key=current_list.index)
# ['1', '1', '2', '3', '4']

Works with any order, sorts on the original order.

current_list = ['2','3','4', '1']
inter = [current_list * max_len][0][:max_len]
sorted(inter, key=current_list.index)
# ['2', '2', '3', '4', '1']

If your list is larger, you can use a more efficient key for the sort, like a dictionary which stores the elements and keys and their index as values.

Here are some other answers discussing sorting like this.

  • Related