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



我有一个看起来像这样的元组列表

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

我想找到索引位置在global_list

  • 包含'John'的元组
  • 包含'Richard'的元组"托马斯">"可汗"在里面

元组可以是('First Name','Last Name')或('Last Name','First Name')。

Thanks in advance

据我所知,您想查找索引。在这种情况下,您需要使用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)

您可以使用np.argwhere(np.array(gloabl_list) == name)[:,0]。要添加更多条件,您可以对所有名称都这样做,或者您可以说:

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

看起来您可能需要一个名称字典,每个名称都有一组索引:

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)

然后,你可以这样做:

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

最新更新