Dharmender Tathgur
Dharmender Tathgur

Reputation: 91

Finding index locations in a list of tuples

I have a list of tuples that looks somewhat like this

global_list = [('Joe','Smith'),('Singh','Gurpreet'),('Dee','Johnson'),('Ahmad','Iqbal')..........]

I want to find index location in global_list of

The tuple could be ('First Name','Last Name') or ('Last Name','First Name').

Thanks in advance

Upvotes: 1

Views: 143

Answers (3)

C.Nivs
C.Nivs

Reputation: 13106

It seems like you might want a dictionary of names, with sets of indices for each name:

global_list = [('Joe', 'Smith'), ('Singh', 'Gurpreet'), ('Dee', 'Johnson'), ('Ahmad', 'Iqbal')]
name_dict = {}

for idx, (first, last) in enumerate(global_list):
    if first not in name_dict:
        name_dict[first] = set(idx)
    else:
        name_dict[first].add(idx)

    if last not in name_dict:
        name_dict[last] = set(idx)
    else:
        name_dict[last].add(idx)

Then, to search you could do:

names = ['Joe', 'Johnson']
indices = set()

for name in names:
    indices.update(name_dict.get(name, set()))

print(indices)
{0, 2}

print([global_list[i] for i in indices])
[('Joe', 'Smith'), ('Dee', 'Johnson')]

Upvotes: 0

Karp
Karp

Reputation: 439

As I understood you want to find indexes. In this situation you need to use enumerate.

indexes_1 = []
indexes_2 = []
for i, tup in enumerate(global_list):
    if "John" in tup:
        indexes_1.append(i)
    if "Richard" in tup or "Thomas" in tup or "Khan" in tup:
        indexes_2.append(i)

Upvotes: 1

user15270287
user15270287

Reputation: 1153

You can use np.argwhere(np.array(gloabl_list) == name)[:,0]. To add in more conditions you can either do this for all the names or you can say:

global_list = np.array(gloabl_list)
np.argwhere((global_list == name1) | (global_list == name2) ...)[:,0]

Upvotes: 0

Related Questions