Skip to content
Advertisement

Problem with comparing two items in a list of lists

I have this list

zipped_values = [(3.0, 4.242640687119285), (3.605551275463989, 3.1622776601683795), (5.0, 3.1622776601683795), (4.123105625617661, 4.47213595499958), (5.0, 4.0), (5.830951894845301, 7.810249675906654), (5.0990195135927845, 5.385164807134504), (7.0710678118654755, 8.06225774829855), (7.0710678118654755, 7.280109889280518), (8.06225774829855, 8.246211251235321)]

what I am trying to do is compare each item within the lists to each other (within the same list), to find out what the minimum is. In the first case, it would be 3.0, in the second, it would be 3.1.

Now what I am trying to do is, if the minimum is the first element, assign that element (3.0) to a dictionary key named M1, and if the minimum is the second element, assign that element to a dictionary key named M2.

This is what I’ve come up with:

  for jk in zipped_value:
    for n in jk:
      if zipped_value[0][n] < zipped_value[0][n+1]:
        dictionary["M1"].append(zipped_value[0][n])

But it gives me this error: TypeError: tuple indices must be integers or slices, not float

What do I do?

Advertisement

Answer

You don’t need the inner loop. jk is the tuple, you just need to compare jk[0] with jk[1]. You can simplify this by unpacking to two variables when looping.

for a, b in zipped_values:
    if a < b:
        dictionary["M1"].append(a)
    else:
        dictionary["M2"].append(b)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement