简体   繁体   中英

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

  • Tuples that have 'John' in them
  • Tuples that have 'Richard' or 'Thomas' or 'Khan' in them

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

Thanks in advance

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)

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]

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')]

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