![](/img/trans.png)
[英]Print the indices of elements in one list according to the values of another list in seperate lines
[英]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
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()
我的代碼 Output:
-1
-1
-1
1 2 6
3 5
預期 Output:
-1
-1
1 2 6
3 5
-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)
Output:
-1
-1
1 2 6
3 5
-1
您可以在此處使用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)
Output:
-1
-1
1 2 6
3 5
-1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.