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

要素がタプルになるまでリスト内の要素をカウントするPythonプログラム?


Aは与えられたリストです。このリストにはネストされたタプルがあります。私たちのタスクは、要素がタプルになるまでリスト内の要素をカウントすることです。ここでは、isinstance()関数を使用します。この関数には2つのパラメーターobjectがあり、classinfo.objectがチェックされ、classinfoはクラス、タイプ、またはクラスとタイプのタプルです。この関数は、オブジェクトがas classのインスタンスまたはサブクラスである場合はtrueを返し、それ以外の場合はタプルの任意の要素を返します。

Input : A=[4, 5, 6, 10,22,33, (1, 2, 3), 11, 2, 4]
Output : 6

アルゴリズム

Step 1: Given a list.
Step 2: Use one counter variable c which is initialized by 0.
Step 3: We traverse the list and verify that encountering a tuple or not in our path of count.
Step 4: If it’s true then counter will be increased by 1 otherwise false.
Step 5: return c

サンプルコード

# Program to count the items 
# until a list is encountered a tuple
def countelement(M): 
   c = 0
   print("RESULT ::>")
   for i in M: 
      if isinstance(i, tuple): 
         break
         c = c + 1     
   return c 
  
# Driver Code 
A = [4, 5, 6, 10,22,33, (1, 2, 3), 11, 2, 4] 
print(countelement(A)) 

出力

Result ::>6

  1. タプル内の要素の出現をカウントするPythonプログラム

    ここでユーザー入力タプルが与えられた場合、私たちのタスクはタプル内の特定の要素の出現をカウントすることです。 例 Input : A = [10, 20, 30, 40, 10, 100, 80, 10] X = 10 Output : 3 アルゴリズム countoccur(A,x) /* A is an array and x is the element to count the number of occurrences */ Step 1: First we use one counter variable which is count the same ele

  2. リストから重複要素を削除する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