Python – 检查列表中的前一个元素是否更小
有时,在使用Python列表时,我们可能会遇到一个问题,即我们需要检查每个元素的前一个元素是否较小。此类问题可用于数据预处理领域。让我们讨论可以执行此任务的某些问题。
Input : test_list = [1, 3, 5, 6, 8]
Output : [True, True, True, True]
Input : test_list = [3, 1]
Output : [False]
方法#1:使用循环
这是可以执行此任务的方式之一。在此,我们使用 brute for in 循环执行检查元素的任务。
Python3
# Python3 code to demonstrate working of
# Check if previous element is smaller in List
# Using loop
# initializing list
test_list = [6, 3, 7, 3, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# Check if previous element is smaller in List
# Using loop
res = []
for idx in range(1, len(test_list)):
if test_list[idx - 1] < test_list[idx]:
res.append(True)
else:
res.append(False)
# printing result
print("List after filtering : " + str(res))
Python3
# Python3 code to demonstrate working of
# Check if previous element is smaller in List
# Using zip() + list comprehension
# initializing list
test_list = [6, 3, 7, 3, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# Check if previous element is smaller in List
# Using zip() + list comprehension
res = [int(sub1) < int(sub2) for sub1, sub2 in zip(test_list, test_list[1:])]
# printing result
print("List after filtering : " + str(res))
输出 :
The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
方法 #2:使用 zip() + 列表理解
这是解决此问题的单线方法。在此,我们首先压缩列表及其下一个元素列表,然后检查比较结果。
Python3
# Python3 code to demonstrate working of
# Check if previous element is smaller in List
# Using zip() + list comprehension
# initializing list
test_list = [6, 3, 7, 3, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# Check if previous element is smaller in List
# Using zip() + list comprehension
res = [int(sub1) < int(sub2) for sub1, sub2 in zip(test_list, test_list[1:])]
# printing result
print("List after filtering : " + str(res))
输出 :
The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]