Home > Software engineering >  Make a new list with a certain order, but skip some indices on if condition
Make a new list with a certain order, but skip some indices on if condition

Time:10-12

I am trying to make an new list in a certain order that relies on another list. It should make an list with an order i specifed, but if an item in that other list is x it should skip that index and continue with the order without skipping an item in the order.

start:

days_list = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
x = 'rest'
order = ['a', 'b', 'c']

after i changed the days_list:

changed_days_list = ['sunday', 'monday', x, 'wednesday', x, 'friday', x]

The output should look like this:

example_output = ['a', 'b', 'rest', 'c', 'rest', 'a', 'rest']

I have tried with for and while loops, but i can't figure it out. Any thoughts?

CodePudding user response:

You could use for-loop to check every value on changed_days_list and put new value from order when it is not rest. And you could use itertools.cycle() to get value from order.

import itertools

x = 'rest'

order = ['a', 'b', 'c']
changed_days_list = ['sunday', 'monday', x, 'wednesday', x, 'friday', x]

cycle = itertools.cycle(order)

result = []

for item in changed_days_list:
    if item == x:
        result.append(item)
    else:
        next_value = next(cycle)
        result.append(next_value)
        
print(result)

Result:

['a', 'b', 'rest', 'c', 'rest', 'a', 'rest']

CodePudding user response:

days_list = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
x = 'rest'
changed_days_list = ['sunday', 'monday', x, 'wednesday', x, 'friday', x]
order = ['a', 'b', 'c']

output_list = []
order_index = 0

for i in changed_days_list:
    if order_index>len(order)-1:
        order_index = 0

    if i == x:
        output_list.append('rest')
    
    elif i != x:
        output_list.append(order[order_index])
        order_index =1

print(output_list)

Output:

['a', 'b', 'rest', 'c', 'rest', 'a', 'rest']
  • Related