首页 文章资讯内容详情

计算Python列表中存在的元素x和x+1

2026-06-04 1 花语

假设我们有一个称为nums的数字列表,我们必须找到存在x+1的元素x的数量。

因此,如果输入类似于[2、3、3、4、8],则输出为3

让我们看下面的实现以更好地理解-

示例

class Solution: def solve(self, nums): s = set(nums) count = 0 for i in nums: if i+1 in s: count += 1 return count ob = Solution() nums = [2, 3, 3, 4, 8] print(ob.solve(nums))

输入项

[2, 3, 3, 4, 8]

输出结果

3