Home > database >  Iterate list to see data that comes earlier
Iterate list to see data that comes earlier

Time:11-09

a_list = [1,3,2,4]
a_data = 3

for a in a_list:
    print(a_data, a)
    if a_data == a:
        if a_data > a:
            print(True)
        else:
            print(False)

i need to do checking of a_list by which

  • the value of a_data need to be higher than value in a_list - will print 'True'
  • but the checking of that condition (a_data > a_list) has to start after the value of a_data equal to value in 'a_list'
  • means that: value 1 in a_list will be ignored as the checking will start at 3.

i am not sure how to do the checking/looping

for the expected output will be

  • 'True' when 3 in a_data met 2 in a_list ---- (3>2)
  • 'False' when 3 in a_data met 4 in a_list ---- (3<2)

CodePudding user response:

If you know fore sure that a_data is in a_list you can find its index and slice a_list with it

a_list = [1, 3, 2, 4]
a_data = 3
index = a_list.index(a_data)
for a in a_list[index:]:
    print(a_data, a)
    if a_data > a:
        print(True)
    else:
        print(False)

Output

3 3
False
3 2
True
3 4
False

CodePudding user response:

You code cannot work as your if a_data > a depends on if a_data == a, which is imcompatible.

If you only want to get True/False for each item depending on a_data you can use a simple list comprehension and filter your initial condition using itertools.dropwhile

a_list = [1,3,2,4]
a_data = 3

from itertools import dropwhile
[a_data>a for a in dropwhile(lambda a: a != a_data, a_list)]

output: [False, True, False]

using a classical loop:
from itertools import dropwhile
for a in dropwhile(lambda a: a != a_data, a_list):
    print(a_data, a)
    print(a_data > a)

output:

3 3
False
3 2
True
3 4
False
  • Related