Search (position) in two-dimensional List

Question:

There is a list:

Aliances=[(1, 'Star Aliance'), (2, 'OneWorld'), (3, 'SkyTeam'), (4, 'Unknown'), (5, 'U-FLY Alliance'), (6, 'SkyTeam Cargo'), (7, 'WOW'), (8, 'Vanilla Alliance'), (9, 'Value Alliance'), (10, 'American Eagle'), (11, 'American Airlines'), (12, 'Sirius Aero'), (10012, 'ASL Aviation Holdings DAC')]

There is a number that is on this list:
PK = 10012

Aliances = S.QueryAliances()
print("Aliances=" + str(Aliances))
myDialog.comboBox_Alliance.clear()
if Aliances:
    for Aliance in Aliances:
        myDialog.comboBox_Alliance.addItem(str(Aliance[1]))
    PKs = []
    for PK in Aliances:
        PKs.append(PK[0])
    print("PKs=" + str(PKs))
    quantity = myDialog.comboBox_Alliance.count()
    index = PKs.index(A.Aliance)
    print("index=" + str(index))
    myDialog.comboBox_Alliance.setCurrentIndex(index)

Tell me please if anyone knows how to get "index" (position of PK=10012) directly from list "Aliances"?

Link to Source Code on my GitHub

Asked By: Tarasov Sergey

||

Answers:

This is actually not a two-dimensional list, but a list of tuples. However, the following should work:

Aliances=[(1, 'Star Aliance'), (2, 'OneWorld'), (3, 'SkyTeam'), (4, 'Unknown'), (5, 'U-FLY Alliance'), (6, 'SkyTeam Cargo'), (7, 'WOW'), (8, 'Vanilla Alliance'), (9, 'Value Alliance'), (10, 'American Eagle'), (11, 'American Airlines'), (12, 'Sirius Aero'), (10012, 'ASL Aviation Holdings DAC')]

index = next((i for i, x in enumerate(Aliances) if x[0] == 10012), None)

print(index)

Output:

12

This also returns None if no match is found. Adapted from this solution.

Answered By: B Remmelzwaal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.