📜  在Python中打印给定整数数组的所有不同元素的程序 |有序字典

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

在Python中打印给定整数数组的所有不同元素的程序 |有序字典


给定一个整数数组,打印数组中所有不同的元素。给定的数组可能包含重复项,并且输出应该只打印每个元素一次。给定的数组未排序。

例子:

Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}
Output: 12, 10, 9, 45, 2

Input: arr[] = {1, 2, 3, 4, 5}
Output: 1, 2, 3, 4, 5

Input: arr[] = {1, 1, 1, 1, 1}
Output: 1

此问题已有解决方案,请参阅 Print All Distinct Elements of a given integer array 链接。我们将使用有序字典在Python中快速解决这个问题。做法很简单,

  1. 使用OrderedDict.fromkeys(iterable)函数将数组转换为字典数据结构,它将任何可迭代的元素转换为字典,其中元素作为 Key 的顺序与它们在数组中出现的顺序相同。
  2. 现在遍历完整的字典并打印键。
# Python program to print All Distinct
# Elements of a given integer array
  
from collections import OrderedDict
  
def printDistinct(input):
     # convert list into ordered dictionary
     ordDict = OrderedDict.fromkeys(input)
  
     # iterate through dictionary and get list of keys
     # list of keys will be resultant distinct elements 
     # in array
     result = [ key for (key, value) in ordDict.items() ]
  
     # concatenate list of elements with ', ' and print
     print (', '.join(map(str, result)))  
  
# Driver program
if __name__ == "__main__":
    input = [12, 10, 9, 45, 2, 10, 10, 45]
    printDistinct(input)

输出:

12, 10, 9, 45, 2