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 < 70condition instead of targeting the 59-character limit you mentioned - Nesting a
forloop inside thewhileloop will cause you to repeatedly cycle throughshortest_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_charsandmax_char_limitmake 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_titlesonce, 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
相关产品推荐
相关产品推荐

