简体   繁体   中英

how to decrease the value of items in a list python

I wanted to find similar items in a list with slightly lower or higher values (0.01 or -0.01) but up to 0.1, example:

real_list = [1.94, 4.72, 8.99, 5.37, 1.33]
list_2 = [1.86, 4.78, 8.91, 5.41, 1.30]

you can see that the values of the two lists are similar, but they are not found in an if, example:



for i in list_2:
    if i in real_list:
        print("found")
    else:
        print("not found")


this code returns me this

not found
not found
not found
not found
not found

I tried to make some modifications but I wanted it to do some combinations decreasing and increasing values in different parts until it found the value in the other list, example:

list_2 = [1.86, 4.78, 8.91, 5.41, 1.30]
1.85
4.77
8.9
5.4
1.29
1.84
4.76

or increase the values until you find it in the list, remembering that it has to be close to 0.1 and nothing more, in short is to find similar values in a list.

Can someone help me?

You need to be sure what you mean when two values are "similar". If I understand you correctly you set an arbitrary threshold of 0.1, for this the code could look something like this:

real_list = [1.94, 4.72, 8.99, 5.37, 1.33]
list_2 = [1.86, 4.78, 8.91, 5.41, 1.30]
threshold = 0.1
for i in list_2:
  found = False
  for j in real_list:
    if abs(i-j) <= threshold:
      print("found")
      found = True
      break
  if not found:
    print("not found")

with a bit of numpy this becomes a rather compact

import numpy as np
real_list = np.array([1.94, 4.72, 8.99, 5.37, 1.33])
list_2 = [1.86, 4.78, 8.91, 5.41, 1.30]
["found" if  np.any(np.isclose(x,real_list,atol=0.04)) else "not found"  for x in list_2]

np.isclose(x,real_list,atol=0.04) does the comparison of each value in list_2 against the whole vector with a given tolerance - can be atol = absolute tolerance and/or rtol : relative tolerance ( https://numpy.org/doc/stable/reference/generated/numpy.isclose.html ).

np.any then reduces the comparison of each value into a single boolean.

You can do something like this:

real_list = [1.94, 4.72, 8.99, 5.37, 1.33]
list_2 = [1.86, 4.78, 8.91, 5.41, 1.30]

for x in real_list:
    for y in list_2:

        if abs(x-y)<0.1:
            print("found",x, "is close to",y)
        else:
            print("not found")

It will run all the itens in your first list, and all itens in your second list and compare if they are less than 0.1 away from eachother.

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