python - 如何检查列表元素是否满足给定条件?
问题描述
我有一个数字列表,其中任何两个相邻数字的总和是一个完美的平方。列表是 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
解决方案
也许是这样的?创建将被调用的函数列表,如果列表满足条件,则返回 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 以及它是否是打印列表和适当的文本。
推荐阅读
- android - 包含 Room-library 会增加应用程序下载大小(~10mb)
- python - 查找任何给定数字的第 n 个数字
- r - 在 R 中看到 left_join 出现意外错误
- java - Is there a a way I can store information with Java without requiring a dedicated server?
- php - woocommerce 基于支付网关的感谢消息
- javascript - Javascript - 如何将数组中对象的第一个元素分配为另一个数组的键
- rest - 更新资源导致位置更改后的 REST 响应
- javascript - How do I return or make null all other EventListeners if another is triggered using vanilla Javascript
- mysql - 在锁定表时重新编号mysql中的主键
- arrays - React:通过字符串映射并为每次迭代发出命令。然后计算结果