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

Python技术实现:列表元素追加至字符限制59时停止

Fixing Your List Appending Logic for 59-Character Limit

Hey there! Let's get your code working exactly as you need—appending elements from one list to another until the total character count hits a 59 limit, stopping if the next element can't fit.

First, let's break down the issues with your current code:

  • You're using a while counter < 70 condition instead of targeting the 59-character limit you mentioned
  • Nesting a for loop inside the while loop will cause you to repeatedly cycle through shortest_titles, adding elements way beyond what you need
  • You're appending elements first and then updating the counter, which could push you over the limit before you realize it

Here's a revised version that follows your requirements perfectly:

shortest_titles = ['Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet', 'TLorem ipsum dolor sit amet', 'Lorem ipsum dolor sit amet']
title_limited = []
total_chars = 0
max_char_limit = 59

for title in shortest_titles:
    # Check if adding this title would stay under the limit
    if total_chars + len(title) <= max_char_limit:
        title_limited.append(title)
        total_chars += len(title)
    else:
        # Can't fit the next element—stop here
        break

print("Final limited list:", title_limited)
print(f"Total characters used: {total_chars}")

Key improvements:

  • Clearer variable names: total_chars and max_char_limit make the code easier to read and adjust later
  • Pre-check before appending: We verify if the next element will fit before adding it, so we never go over the 59-character limit
  • Single loop: We iterate through shortest_titles once, stopping as soon as we hit the limit instead of looping repeatedly
  • Explicit break: As soon as an element can't fit, we exit the loop immediately

If you run this, you'll see it stops adding elements the moment adding the next one would exceed 59 characters—exactly what you wanted!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:55:28