简体   繁体   中英

Most efficient way to loop over python list and compare and adjust element values

I have a list of elements with a certain attribute/variable. First of all I need to check if all attributes have the same value, if not I need to adapt this attribute for every element to the highes value. The thing is, it is not difficult to programm such a loop. However, I would like to know what the most efficient way is to do so.

My current approach works fine, but it loops through the list 2 times, has two local variables and just does not feel efficient enough.

I simplified the code. This is basically what I've got:

    biggest_value = 0
    re_calc = 0
    for _, element in enumerate(element_list):
        if element.value > biggest_value :
            biggest_value = element.value
            re_calc += 1
    if re_calc > 1:
        for _, element in enumerate(element_list):
            element.value = adjust_value(biggest_value)
            element_list(_) = element

The thing annoying me is the necessity of the "re_calc" variable. A simple check for the biggest value is no big deal. But this task consists out of 3 steps: "Compare Attributes--> Finding Biggest Value --> possibly Adjust Others". However I do not want to loop over this list 3 times. Not even two times as my current suggestion does.

There has to be a more efficient way. Any ideas? Thanks in advance.

The first loop is just determing the largest value of the element_list. So an approach can be: transform the element_list into a numpy array. Unfortunately you do not tell, how the list looks like. But if the list contains numbers then L = np.array(element_list) can probably do it. After that use np.max(L) . Numpy commands without for loops are usually much faster.

import numpy as np
nl = 10
L = np.random.rand(nl)
biggest_value = np.max(L)
L, biggest_value

gives

(array([0.70047074, 0.14160459, 0.75061621, 0.89013494, 0.70587705,
        0.50218377, 0.31197993, 0.42670057, 0.67869183, 0.04415816]),
 0.8901349369179461)

In the second for-loop it is not obvious what you want to achieve. Unfortunately you do not give an input and a desired output and do not not tell what adjust_value has to do. A minimal running code with data would be helpful to give a support.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM