Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

python - Print only once after max is reached

I need to execute the final print statement only once, after max_rows is reached.

Let's say you need to fill a list with 30 elements, but only want to print the first 20 times, then simply want to keep appending to the list without printing anything, except "Truncating..." (once).

This is an ugly way to accomplish this. What could be a more elegant approach?

max_rows = 20
max_rows_exceeded = False
rows = 0
i = 0
my_list = list()
while i < 30:
    i += 1
    if rows < max_rows:
        print("rows < max_rows  -   %s" % rows)
        rows += 1
    else:
        max_rows_exceeded = True
    my_list.append(i)
if max_rows_exceeded:
    print("Truncating due to max displayable row number exceeded: %s" % max_rows)
question from:https://stackoverflow.com/questions/65904886/print-only-once-after-max-is-reached

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no reason to check if the rows exceeded inside the loop. You can check this "mathematically" after the loop:

max_rows = 20
my_list = []

upper_limit = 30
for rows in range(upper_limit):
    if rows < max_rows:
        print("rows < max_rows  -   %s" % rows)
    my_list.append(rows)

if max_rows < upper_limit:
    print("Truncating due to max displayable row number exceeded: %s" % max_rows)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...