【问题标题】:Print the indices of elements in one list according to the values of another list in seperate lines and print -1 for missing elements in python根据单独行中另一个列表的值打印一个列表中元素的索引,并为python中的缺失元素打印-1
【发布时间】:2020-08-24 19:08:32
【问题描述】:
A = [['a'],['a'],['b'],['c'],['b'],['a']]

B = [['k'],['k'],['a'],['b'],['k']]

我有两个列表,A 和 BI 必须打印由列表 A 的空格分隔的那些元素索引号(索引号 + 1),这些元素也存在于列表 B 中。对于列表 B 的每个元素,我想打印列表 A 中值的索引在一行中按顺序排列。如果列表 B 中的任何元素在列表 A 中丢失,那么我想为这个元素打印 -1。我该如何解决这个问题?

我的代码:

dict_B = dict([(b[0],[]) for b in B])

for i,a in enumerate(A):
    if a[0] in dict_B:
        dict_B[a[0]].append(i+1)

for key in dict_B:
    if dict_B[key] == []:
        c = 0
        for i,x in enumerate(B):
            if x == list(key):
                c += 1
        for x in range(c):
            if x == c-1:
                print(-1,end=" ")
            else:
                print(-1)
    else:
        for elem in dict_B[key]:
            print(elem,end=' ')
    print()

我的代码输出:

-1
-1
-1 
1 2 6 
3 5 

预期输出:

-1
-1
1 2 6
3 5
-1

【问题讨论】:

    标签: python python-3.x list indices


    【解决方案1】:

    你把问题复杂化了,我不知道你为什么需要使用dict

    for item_b in B:
        found = []
        for i, item_a in enumerate(A):
            if item_a == item_b:
                found.append(str(i + 1))
        print(" ".join(found) or -1)
    

    输出:

    -1
    -1
    1 2 6
    3 5
    -1
    

    【讨论】:

      【解决方案2】:

      您可以在此处使用collections.defaultdict

      from collections import defaultdict
      idx_dict=defaultdict(list)
      
      for idx,[val] in enumerate(A,1):
          idx_dict[val].append(idx)
      
      for [key] in B:
          if key in idx_dict:
              print(' '.join(map(str,idx_dict[key])))
          else:
              print(-1)
      

      输出:

      -1
      -1
      1 2 6
      3 5
      -1
      

      【讨论】:

        猜你喜欢
        • 2020-08-17
        • 2021-10-01
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多