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

リスト内の符号変更のインデックスを取得するPythonプログラム


リスト内の符号変更のインデックスを取得する必要がある場合は、「追加」メソッドとともに単純な反復を使用できます。

以下は同じもののデモンストレーションです

my_list = [71, 24, -34, -25, -76, 87, 29, -60, 70, 8]

print("The list is :")
print(my_list)
my_result = []
for index in range(0, len(my_list) - 1):

   if my_list[index] > 0 and my_list[index + 1] < 0 or my_list[index] < 0 and my_list[index + 1] < 0:

      my_result.append(index)

print("The result is :")
print(my_result)

出力

The list is :
[71, 24, -34, -25, -76, 87, 29, -60, 70, 8]
The result is :
[1, 2, 3, 6]

説明

  • リストが定義され、コンソールに表示されます。

  • 空のリストが定義されています。

  • 元のリストが繰り返され、特定のインデックスの値が0より小さいか大きいかをチェックする条件が設定されます。

  • これに応じて、インデックスが空のリストに追加されます。

  • これは、コンソールに出力として表示されます。


  1. リストから一意の値を出力するPythonプログラム

    リストが与えられた場合、私たちのタスクはすべての一意の番号を印刷することです。 例 Input:A = [1, 2, 3, 4, 2, 1, 9] Unique list is [1, 2, 3, 4, 9] アルゴリズム Step 1: Create user input list. Step 2: Create an empty list. Step 3: Traverse all elements in the list. Step 4: Check the unique element is present or not. Step 5: Append unique element o

  2. リストのすべてのサブリストを出力するPythonプログラム。

    リストを指定して、リストのすべてのサブリストを印刷します。 例- Input : list = [1, 2, 3] Output : [], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] アルゴリズム Step 1 : given a list. Step 2 : take one sublist which is empty initially. Step 3 : use one for loop till length of the given list. Step 4 : Run a loop from i+1 to length of th