简体   繁体   English

在元组列表中查找索引位置

[英]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我想在 global_list 中找到索引位置

  • Tuples that have 'John' in them包含“John”的元组
  • Tuples that have 'Richard' or 'Thomas' or 'Khan' in them包含“Richard”“Thomas”“Khan”的元组

The tuple could be ('First Name','Last Name') or ('Last Name','First Name').元组可以是 ('First Name','Last Name') 或 ('Last Name','First Name')。

Thanks in advance提前致谢

As I understood you want to find indexes.据我了解,您想查找索引。 In this situation you need to use enumerate .在这种情况下,您需要使用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] .您可以使用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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM