用于获取列表中符号变化索引的Python程序
给定 List,任务是编写一个Python程序,提取发生符号偏移的所有索引。
Input : test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Output : [1, 4, 6, 7]
Explanation : 6 -> -3, at 1st index, -7 -> 8 at 4th index and so on are shifts.
Input : test_list = [7, 6, -3, -4, -7, 8, 3, 6, 7, 8]
Output : [1, 4]
Explanation : 6 -> -3, at 1st index, -7 -> 8 at 4th index are shifts.
方法 1:使用循环和条件语句
在这里,我们使用条件语句检查当前元素和下一个元素是否具有相反的符号。循环用于遍历所有元素。
例子:
Python3
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
res = []
for idx in range(0, len(test_list) - 1):
# checking for successive opposite index
if test_list[idx] > 0 and test_list[idx + 1] < 0 or test_list[idx] < 0 and test_list[idx + 1] > 0:
res.append(idx)
# printing result
print("Sign shift indices : " + str(res))
Python3
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to provide one liner alternative
res = [idx for idx in range(0, len(test_list) - 1) if test_list[idx] >
0 and test_list[idx + 1] < 0 or test_list[idx] < 0 and test_list[idx + 1] > 0]
# printing result
print("Sign shift indices : " + str(res))
输出:
The original list is : [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Sign shift indices : [1, 4, 6, 7]
方法 2:使用列表理解
与上述方法类似,但这提供了一种使用列表理解的单行替代方法。
例子:
蟒蛇3
# initializing list
test_list = [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to provide one liner alternative
res = [idx for idx in range(0, len(test_list) - 1) if test_list[idx] >
0 and test_list[idx + 1] < 0 or test_list[idx] < 0 and test_list[idx + 1] > 0]
# printing result
print("Sign shift indices : " + str(res))
输出:
The original list is : [7, 6, -3, -4, -7, 8, 3, -6, 7, 8]
Sign shift indices : [1, 4, 6, 7]