how to update a list value, without matching index

Viewed 111

Hello I am trying to update a list of order numbers and their times. For example, I have four lists that look like this

    OrderNum1 = ['1','6','3']
    originaltime = ['12AM','5AM','7AM']

    OrderNum2 = ['1','3']
    newtime = ['2AM','2AM']

The Goal is to replace the values of 'originaltime' with the values of 'newtime' if/when the order numbers match.

I was previously using this

    for i,(a,b) in enumerate(zip(OrderNum1,OrderNum2)):
    if a == b:
    originaltime[i] = newtime[i]

But that will not update the time of ordernum 3 because the index does not match. The desired outcome is:

    print(originaltime)
    ['2AM', '5AM', '2AM']
7 Answers

You were close! Have a look at this:

trans = {k: v for k, v in zip(OrderNum2, newtime)}

originaltime = [trans.get(k, item) for k, item in zip(OrderNum1, originaltime)]
print(originaltime)  # -> ['2AM', '5AM', '2AM']

try this:

for i in OrderNum2:
    pos2 = OrderNum2.index(i)
    for j in OrderNum1:
        pos1 = OderNum1.index(j)
        if i == j:
            originaltime[pos1] = newtime[pos2]

You could build a OrderNum2-to-newtime dict() to lookup the replacement values when the order numbers match, if no match it uses the original time:

OrderNum1 = ['1', '6', '3']
originaltime = ['12AM', '5AM', '7AM']

OrderNum2 = ['1', '3']
newtime = ['2AM', '2AM']


new_times = dict(zip(OrderNum2, newtime))
originaltime = [new_times.get(order_num, org_time) for order_num, org_time in zip(OrderNum1, originaltime)]

print(originaltime)

Output:

['2AM', '5AM', '2AM']

You can try

originaltime = [originaltime[i] if v not in OrderNum2 else newtime[OrderNum2.index(v)] for i, v in enumerate(OrderNum1)]
print(originaltime)

Output

['2AM', '5AM', '2AM']

You can use this for loop to fill in the gaps:

OrderNum1 = ['1','6','3']
originaltime = ['12AM','5AM','7AM']

OrderNum2 = ['1','3']
newtime = ['2AM','2AM']

for i,(a,b) in enumerate(zip(OrderNum1,OrderNum2)):
    if a != b:
        OrderNum2.insert(i,' ')
        newtime.insert(i,' ') 
    else:
        originaltime[i] = newtime[i]
        
print(originaltime)

Output:

['2AM', '5AM', '2AM']

I always enjoy list manipulation question! There are plenty of ways to approach this problem, but I'll try and give a solution similar to your attempt.

OrderNum1 = ['1','6','3']
originaltime = ['12AM','5AM','7AM']

OrderNum2 = ['1','3']
newtime = ['2AM','2AM']

for i, val in enumerate(OrderNum2):
    if val in OrderNum1:
        originaltime[int(val) - 1] = newtime[i]

print(originaltime)

I try to write same answer with dictionary as simple as i can:

dict2 = dict()  # create a dictionary
for i in range(len(OrderNum2)):
    dict2[OrderNum2[i]] = newtime[i]
# your dictionary created

for j in range(len(OrderNum1)):
    if dict2.get(OrderNum1[j]):
        originaltime[j] = dict2.get(OrderNum1[j])

print(originaltime)
Related