Home > Mobile >  python - How to compare each value(float) in list
python - How to compare each value(float) in list

Time:12-09

i have 4 list i need to compare 2 list if list1 > list2 get a value from list3, if list1 < list2 get a value from list4

This my lates Code: `

number_list_1 = [1.15679, 0.042, 0.88773]
number_list_2 = [1.157, 0.443434343, 0.0948887]
al = [5, 10, 100]
bl = [4, 200, 24]


arr_rs = []
for i,j in zip(number_list_1, number_list_2):
    if i > j:
        for a in al:
            arr_rs.append(a)
    if i < j :
        for b in bl:
            arr_rs.append(b)
        break
print(arr_rs)

i expecting this output:

[4,200,100] but when i run the get this output: [4,200,24]

CodePudding user response:

Changes made:-

(1) No need to use for loop instead you can apply one pass. indexer in my code

Code:-

number_list_1 = [1.15679, 0.042, 0.88773]
number_list_2 = [1.157, 0.443434343, 0.0948887]
al = [5, 10, 100]
bl = [4, 200, 24]


arr_rs = []
indexer=0
for i,j in zip(number_list_1, number_list_2):
    if i > j:
        arr_rs.append(al[indexer])
    if i < j :
        arr_rs.append(bl[indexer])
    indexer =1   
print(arr_rs)

Output:-

[4, 200, 100]

Using Enumerate:-

number_list_1 = [1.15679, 0.042, 0.88773]
number_list_2 = [1.157, 0.443434343, 0.0948887]
al = [5, 10, 100]
bl = [4, 200, 24]


arr_rs = []

for indexer,j in enumerate(zip(number_list_1, number_list_2)):
    if j[0] > j[1]:
        arr_rs.append(al[indexer])
    elif j[0] < j[1] :
        arr_rs.append(bl[indexer])
print(arr_rs)

Output:- Same as above..

Using zip():-

number_list_1 = [1.15679, 0.042, 0.88773]
number_list_2 = [1.157, 0.443434343, 0.0948887]
al = [5, 10, 100]
bl = [4, 200, 24]


arr_rs = []
for a,b,c,d in zip(number_list_1,number_list_2,al,bl):
    if a > b:
        arr_rs.append(c)
    elif a < b :
        arr_rs.append(d)
print(arr_rs)

Output:- Same as 1st code

CodePudding user response:

You can do it in one line thanks to a list comprehension and the ternary conditional operator.

I find it quite readable for a one-liner.

Also enumerate() is useful here to deal with indexes.

arr_rs = [al[i] if x > y else bl[i] for i, (x, y) in enumerate(zip(number_list_1, number_list_2))]

CodePudding user response:

number_list_1 = [1.15679, 0.042, 0.88773]
number_list_2 = [1.157, 0.443434343, 0.0948887]
al = [5, 10, 100]
bl = [4, 200, 24]

arr_rs = []
for i, j in zip(number_list_1, number_list_2):
    if i > j:
        arr_rs.append(al[number_list_1.index(i)])
    elif i < j:
        arr_rs.append(bl[number_list_1.index(i)])
print(arr_rs)

Try this.

  • Related