用 Python 编写的删除列表中重复条目的程序

pythonserver side programmingprogramming更新于 2026/2/2 14:36:17

假设我们有一个名为 nums 的数字列表,我们必须删除列表中多次出现的数字,还必须保持原始列表中出现的顺序。

因此,如果输入为 nums = [2, 4, 6, 1, 4, 6, 9],则输出将为 [2, 1, 9],因为这些元素只出现过一次。

为了解决这个问题,我们将遵循以下步骤 −

  • dict := 一个新的映射
  • 对于 nums 中的每个 i,执行
    • 如果 i 不在 dict 中,则
      • dict[i] := 0
    • dict[i] := dict[i] + 1
  • 返回一个列表,其中包含 nums 中的所有元素 e,其中 dict[e] 为 1

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def solve(self, nums):
      dict = {}
      for i in nums:
         if i not in dict:
            dict[i] = 0
         dict[i] = dict[i] + 1
      return [k for k, v in dict.items() if v == 1]
ob = Solution()
nums = [2, 4, 6, 1, 4, 6, 9] print(ob.solve(nums))

输入

[2, 4, 6, 1, 4, 6, 9]

输出

[2, 1, 9]

相关文章


有用资源