Python程序从列表中以数字递增的顺序提取元素
给定元素列表,提取所有数字按顺序递增的元素。
Input : test_list = [1234, 7373, 3643, 3527, 148, 49]
Output : [1234, 148, 49]
Explanation : All elements have increasing digits.
Input : test_list = [12341, 7373, 3643, 3527, 1481, 491]
Output : []
Explanation : No elements have all increasing digits.
方法 1:使用循环和str()
在这里,我们将每个元素转换为字符串,然后使用循环检查它们的每个数字是否大于前一个数字。
Python3
# initializing list
test_list = [1234, 7373, 3643, 3527, 148]
# printing original list
print("The original list is : " + str(test_list))
# loop to check for each element
res = []
for ele in test_list:
flag = True
for idx in range(len(str(ele)) - 1):
# checking for each next digit
if str(ele)[idx + 1] <= str(ele)[idx]:
flag = False
if flag:
res.append(ele)
# printing result
print("Extracted increasing digits : " + str(res))
Python3
# initializing list
test_list = [1234, 7373, 3643, 3527, 148]
# printing original list
print("The original list is : " + str(test_list))
# sorting and comparing for equality
res = [ele for ele in test_list if ''.join(sorted(str(ele))) == str(ele)]
# printing result
print("Extracted increasing digits : " + str(res))
输出:
The original list is : [1234, 7373, 3643, 3527, 148]
Extracted increasing digits : [1234, 148]
方法 2:使用sorted() 、列表推导和str()
在此,我们通过对每个元素进行排序并与原始版本进行比较来测试元素的每个数字是否增加。如果它们相同,则将该元素添加到所需列表中。
蟒蛇3
# initializing list
test_list = [1234, 7373, 3643, 3527, 148]
# printing original list
print("The original list is : " + str(test_list))
# sorting and comparing for equality
res = [ele for ele in test_list if ''.join(sorted(str(ele))) == str(ele)]
# printing result
print("Extracted increasing digits : " + str(res))
输出:
The original list is : [1234, 7373, 3643, 3527, 148]
Extracted increasing digits : [1234, 148]