📜  Python - 元素索引目录

📅  最后修改于: 2022-05-13 01:54:26.570000             🧑  作者: Mango

Python - 元素索引目录

给定一个元素列表,任务是编写一个Python程序来计算所有元素的所有索引。

例子:

Input: test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8]
Output: {8: [4, 8], 3: [2, 5], 6: [1, 6], 7: [0, 3, 7]}
Explanation: 8 occurs at 4th and 8th index, 3 occurs at 2nd and 5th index and so on.

Input: test_list = [7, 6, 3, 7, 8, 3, 6]
Output: {8: [4], 3: [2, 5], 6: [1, 6], 7: [0, 3]}
Explanation: 8 occurs at 4th index, 3 occurs at 2nd and 5th index and so on.

方法一:使用字典理解 + enumerate() + set()

在此,我们使用enumerate()获取所有索引以附加到索引列表以匹配值。字典理解用于列表中所有元素的迭代。 set()用于获取所有元素而不重复。

Python3
# Python3 code to demonstrate working of
# Index Directory of Elements
# Using dictionary comprehension + enumerate()
  
# initializing list
test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting each element index values
res = {key: [idx for idx, val in enumerate(test_list) if val == key]
       for key in set(test_list)}
  
# printing result
print("Index Directory : " + str(res))


Python3
# Python3 code to demonstrate working of
# Index Directory of Elements
  
# Using dictionary comprehension + groupby() + 
# enumerate() + sorted() + itemgetter()
from itertools import groupby
from operator import itemgetter
  
# initializing list
test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# after grouping after sorting
# and rearranging and assigning values with index
res = {key: [idx for idx, _ in groups] for key, groups in groupby(
    sorted(enumerate(test_list), key=itemgetter(1)), key=itemgetter(1))}
  
# printing result
print("Index Directory : " + str(res))


输出:

The original list is : [7, 6, 3, 7, 8, 3, 6, 7, 8]
Index Directory : {8: [4, 8], 3: [2, 5], 6: [1, 6], 7: [0, 3, 7]}

方法 #2:使用字典理解 + groupby() + enumerate() + sorted() + itemgetter()

在这里,我们使用groupby()sorted()对元素进行排序和分组。 itemgetter()用于获取按索引中的值和使用enumerate()提取的值排序的值。字典理解用于获得分组结果的配对索引。

蟒蛇3

# Python3 code to demonstrate working of
# Index Directory of Elements
  
# Using dictionary comprehension + groupby() + 
# enumerate() + sorted() + itemgetter()
from itertools import groupby
from operator import itemgetter
  
# initializing list
test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8]
  
# printing original list
print("The original list is : " + str(test_list))
  
# after grouping after sorting
# and rearranging and assigning values with index
res = {key: [idx for idx, _ in groups] for key, groups in groupby(
    sorted(enumerate(test_list), key=itemgetter(1)), key=itemgetter(1))}
  
# printing result
print("Index Directory : " + str(res))

输出:

The original list is : [7, 6, 3, 7, 8, 3, 6, 7, 8]
Index Directory : {3: [2, 5], 6: [1, 6], 7: [0, 3, 7], 8: [4, 8]}