用 Python 编写程序计算包含奇数位的列表中元素的数量
pythonserver side programmingprogramming更新于 2026/1/12 1:48:17
假设我们有一个名为 nums 的正数列表,我们必须找出具有奇数位的元素的数量。
因此,如果输入为 [1, 300, 12, 10, 3, 51236, 1245],则输出为 4
要解决这个问题,我们将遵循以下步骤 −
- c:= 0
- 对于范围从 0 到 nums 大小的 i,执行
- s:= nums[i] 的数字计数
- 如果 s 为奇数,则
- c:= c+1
- 返回 c
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): c=0 for i in range(len(nums)): s=len(str(nums[i])) if s%2!=0: c=c+1 return c ob = Solution() print(ob.solve([1, 300, 12, 10, 3, 51236, 1245]))
输入
[1, 300, 12, 10, 3, 51236, 1245]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

