📌  相关文章
📜  Python程序从列表中以数字递增的顺序提取元素

📅  最后修改于: 2022-05-13 01:55:08.416000             🧑  作者: Mango

Python程序从列表中以数字递增的顺序提取元素

给定元素列表,提取所有数字按顺序递增的元素。

方法 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]