Python
 Computer >> コンピューター >  >> プログラミング >> Python

リストから重複要素を削除するPythonプログラム?


1つのリストには重複要素が含まれています。私たちのタスクは、重複なしの要素を含む別のリストを作成することです。

A::[2,3,4,3,4,6,78,90]
Output::[2,3,4,6,78,90]

アルゴリズム

Step 1: create a list.
Step 2: create a new list which is empty.
Step 3: traverse every element in list.
Step 4: if element is not present in the list return true.
Step 5: append in the new list.
Step 6: display new list.

サンプルコード

#  To remove duplicate elements
defremoveduplicateele(A):
   newlist = []
   for n in A:
      if n not in newlist:
         newlist.append(n)
   returnnewlist
# Driver Code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the number ::")
fori in range(int(n)):
   k=int(input(""))
   A.append(int(k))
print("THE NEW LIST IS ::>",removeduplicateele(A))

出力

Enter the size of the List ::5
Enter the number ::
10
20
30
20
10
THE LIST IS ::> [10, 20, 30]

  1. リストからN個の最大の要素を見つけるPythonプログラム

    整数リストが与えられた場合、私たちのタスクはリスト内で最大のN個の要素を見つけることです。 例 Input : [40, 5, 10, 20, 9] N = 2 Output: [40, 20] アルゴリズム Step1: Input an integer list and the number of largest number. Step2: First traverse the list up to N times. Step3: Each traverse find the largest value and store it in a new list. 例 def Nnumbere

  2. Pythonでインデックスによってリストから要素を削除するにはどうすればよいですか?

    リスト内のインデックスで要素を削除するには、2つのオプションがあります。 delステートメントを使用し、pop()メソッドを使用します。 delステートメントには、削除する要素のインデックスが必要です。 >>> L1=[11,22,33,44,55,66,77] >>> del L1[2] >>> L1 [11, 22, 44, 55, 66, 77] 組み込みリストクラスのpop()メソッドには、引数としてインデックスが必要です。このメソッドは、削除された要素を返し、リストの内容を1要素減らします。 >>> L1=[