You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.x:检测含正整数的10元素行并输出行号

问题与解决方案

问题描述

刚接触Python,正在学习简单循环与通用输入输出逻辑。已实现以下功能:

  • 生成用户指定长度的随机整数列表(整数取值范围为-100至100),并按每行10个元素的格式打印
  • 统计列表中正整数的总数

但无法实现检测至少包含一个正整数的行,并输出对应行号的功能,当前编写的rows_with_positives函数运行时卡顿无法完成,尝试过for循环也未解决。

原代码

import random
import math
import itertools as it

def round_up(n, decimals=0):
    multiplier = 10**decimals
    return math.ceil(n * multiplier) / multiplier

def main():
    global L
    print("How many numbers would you like to create?")
    N = int(input(""))
    print("")
    print("")
    
    L = []

    for s in range(0, N):
        R = random.randint(-100, 100)
        L.append(R)

    for s in range(0, len(L), 10):
        print(*L[s:s+10])
        print("")
    
    return L

def positive_number_count():
    C = 0
    S = 0
    Len = len(L)-1
    
    while S<=Len:
        if L[S]>0:
            C=C+1
            S=S+1
        else:
            S=S+1
        if S>Len:
            break
    
    print(f'There are {C} positive numbers!')
    

def rows_with_positives():
    value=0
    while value<len(L):
        if L[value]>0:
            print(L[value])
            value=int(round_up(value, -1))
            if value>len(L):
                break
        if value>len(L):
            break

问题分析

原rows_with_positives函数卡顿的核心原因是死循环:当遍历到非正整数时,value变量不会递增,导致一直停留在当前位置重复判断,无法推进循环。同时逻辑上未完整遍历每行所有元素,仅通过单个元素判断行是否符合条件,存在判断遗漏。

修复后的代码

import random
import math

def round_up(n, decimals=0):
    multiplier = 10**decimals
    return math.ceil(n * multiplier) / multiplier

def main():
    print("How many numbers would you like to create?")
    N = int(input())
    print("\n")
    
    num_list = []
    for _ in range(N):
        num_list.append(random.randint(-100, 100))

    # 按每行10个元素打印
    for idx in range(0, len(num_list), 10):
        print(*num_list[idx:idx+10])
        print("")
    
    return num_list

def positive_number_count(num_list):
    count = 0
    for num in num_list:
        if num > 0:
            count += 1
    print(f'There are {count} positive numbers!')

def rows_with_positives(num_list):
    print("包含正整数的行号:")
    # 按行遍历,行号从1开始计数
    for row_start in range(0, len(num_list), 10):
        current_row = num_list[row_start:row_start+10]
        # 快速判断当前行是否存在正整数
        has_positive = any(num > 0 for num in current_row)
        if has_positive:
            # 计算实际行号(从1开始)
            print(f"第 {row_start//10 + 1} 行")

if __name__ == "__main__":
    nums = main()
    positive_number_count(nums)
    rows_with_positives(nums)

关键改进点

  1. 移除全局变量:将生成的列表作为参数传递给其他函数,避免全局变量带来的逻辑混乱
  2. 简化正整数统计:用for循环直接遍历列表,逻辑更清晰,执行效率更高
  3. 修复行检测逻辑:
    • 按每10个元素为一组遍历,确保覆盖所有行
    • 使用any()函数快速判断行内是否存在正整数,代码简洁高效
    • 行号从1开始计数,符合日常使用习惯
  4. 代码规范优化:变量名更具可读性,移除无用的itertools导入,简化输入处理

内容的提问来源于stack exchange,提问作者Alexis Otter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 17:28:27