【问题标题】:Finding index locations in a list of tuples在元组列表中查找索引位置
【发布时间】:2021-05-30 13:36:45
【问题描述】:

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

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

我想在 global_list of

中查找 索引位置
  • 其中包含“John”的元组
  • 元组中包含“Richard”“Thomas”“Khan”

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

提前致谢

【问题讨论】:

标签: python numpy tuples


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用np.argwhere(np.array(gloabl_list) == name)[:,0]。要添加更多条件,您可以对所有名称执行此操作,也可以说:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 2023-03-15
        • 2019-05-27
        • 1970-01-01
        • 2013-07-26
        • 2021-06-25
        相关资源
        最近更新 更多