Home > other >  How to compare the value of each element in two different lists and update one of them with constant
How to compare the value of each element in two different lists and update one of them with constant

Time:06-08

map = [i * 1000 for i in ap]
mtp = [i * 1000 for i in tp]
print(map)
print(mtp)


while True:
    for i in mtp:
        pass
    for j in map:
        if map[map.index(j)] < mtp[mtp.index(i)]:
            print(map)
            map[map.index(j)]  = 110
map= [23000, 23000, 19000, 18000, 36000, 27000, 26000, 17000, 40000, 37000, 36000, 23000, 40000, 14000, 24000]

mtp= [48000, 59000, 33000, 31000, 46000, 38000, 38000, 28000, 60000, 47000, 52000, 45000, 50000, 27000, 35000]

I want to increase the value of each element in the list 'map' by 110 in every iteration, and make sure that the value of the element in map will not exceed the value of the element in mtp in the SAME position. For example, the first element in map is 23000 and it should reach to 48000 because the first element in mtp is 48000 by increasing 110 in every iteration, it may not be equal, but the important point does not exceed the 48000. The last updated value of the list when I run this code is

[35100, 35100, 35060, 35050, 36000, 35030, 35020, 35040, 40000, 37000, 36000, 35100, 40000, 34900, 35000]

almost all values reached 35000 and did not go any further. The ones above 35000 stayed so from the beginning.

CodePudding user response:

Try this. Instead of adding in iteration, find the number of times you need to iterate first, then just multiply and add

# the number of times 110 must be added to values in map 
# until they reach corresponding values in mtp
multipliers = [int((j-i)/110) for i, j in zip(map, mtp)]
# add the differences
res = [i   m * 110 for i, m in zip(map, multipliers)]
res
# [47970, 58970, 32970, 30980, 45900, 38000, 37990, 28000, 59910, 46900, 51950, 45000, 49900, 26980, 35000]

If you want to see the progress, use

# initialize set of indices
indices = set(range(len(mtp)))
# while there are indices
while indices:
    # go through the list of indices
    # and update map elements if less than mtp element in the same index
    # if not, remove the index from indices
    for i in list(indices):
        if map[i]   110 <= mtp[i]:
            map[i]  = 110
        else:
            indices.remove(i)
    #print(map)
map
# [47970, 58970, 32970, 30980, 45900, 38000, 37990, 28000, 59910, 46900, 51950, 45000, 49900, 26980, 35000]
  • Related