首页 > 解决方案 > 如何检查列表元素是否满足给定条件?

问题描述

我有一个数字列表,其中任何两个相邻数字的总和是一个完美的平方。列表是 x=[1,8,28,21,4,32,17,19,30,6,3,13,12,24]

for i in range(len(x)-1):
    y= x[i]+x[i+1]
    z=y**0.5
    #till here found the square root of the sum of the adjacent numbers in list
    if(z.is_integer==True):
        //code

我想检查列表中的剩余数字。如果列表的所有元素都满足条件。然后我想打印列表

预期的输出应该是

[1,8,28,21,4,32,17,19,30,6,3,13,12,24] satisfies the condition

标签: pythonlist

解决方案


也许是这样的?创建将被调用的函数列表,如果列表满足条件,则返回 True,否则返回 False。

def some_function(nums):
   for i in range(len(nums) - 1):
      y = nums[i] + nums[i + 1]
      z = y ** 0.5
      #till here found the square root of the sum of the adjacent numbers in list
      if z.is_integer() not True:
         # if there is some two numbers that don't meet condition, function will return False
         return False
   return True

你这样称呼它:meet_condition = some_function(x) 之后只需检查它是否为 True 以及它是否是打印列表和适当的文本。


推荐阅读