Home > Net >  In what object can i add both lists and floats so i can find the list with the lowest float value
In what object can i add both lists and floats so i can find the list with the lowest float value

Time:10-26

Say i have some iterations. In each iteration, a list of integers and a float number are created.

1st iteration: [0,2,4,3,0] , 285 are created
2nd iteration: [0,8,5,6,0] , 230 are created
...
nth iteration: [0,9,8,1,0] , 340 are created

I want to iteratively append each list-float pair to an object, so I can later get the list with the lowest float value. Desired output could be for example something like this:

ListColumn, FloatColumn
[0,2,4,3,0], 285
[0,8,5,6,0], 230
...
[0,9,8,1,0], 340

I tried to append these lists and floats to a dictionary (with floats as keys) but since some floats can be equal, the number of elements inside the dictionary is less than expected. Any ideas?

CodePudding user response:

I want to iteratively append each list-float pair to an object, so I can later get the list with the lowest float value.

Reading the motivation literally, "so I can later get the list with the lowest float value," suggests that you don't want a data structure at all. Rather, you want to simply assign minimum = float('inf') (or assign it the 1st value), and then keep assigning smallest_list to be each list you encounter that is associated with smaller value than minimum.

But if you really really want to create a large data structure for this, a list of tuples would be a good fit.

def get_pairs():
    # Presumably some `for` loop knows how to generate these for real.
    yield 285, [0,2,4,3,0]
    yield 230, [0,8,5,6,0]
    ...
    yield 340, [0,9,8,1,0]


val, lst = sorted(get_pairs())[0]  # The zero-th element has the minimum.
print(lst)

CodePudding user response:

You could still create a dictionary, but if the float value is already in the dictionary, you append it to the existing lists.

# create dictionary
d = {}

for i in range(n):
    # get your float value and list from somewhere
    float_value, l = create_float_and_list()
    # if the float value already exists, append the new lists to the existing lists, otherwise create new dictionary entry
    if float_value in d.keys():
        d[float_value].append(l)
    else:
        d[float_value] = [l]

float_values = list(d.keys())
min_value = min(float_values)
# output list of lists with the given float value
print(d[min_value])
  • Related