不使用第三方库生成指定连续元素列表的技术问题咨询
Hey there! Let's break down how to solve this problem properly. I see you're trying to create those 10-element chunks without numpy, and you're stuck on loop logic—especially the termination condition and carrying over the starting value from the previous chunk. Also, I noticed your target output skips the 51-60 range, so we'll need to account for that gap too.
First, Let's Fix Your Existing Code Issues
Your current snippet has a couple of clear problems:
for i in len(arr)will throw an error becauselen(arr)returns an integer (10 here), and you can't iterate over an integer. You'd needrange(len(arr))if you wanted to loop over indices, but that's not the right approach for this task.start=[-1]is a list, but you need a single integer to track the starting value of each new chunk.
Simple Single-Loop Implementation
Here's a straightforward approach that tracks the starting value of each chunk, skips the 51-60 range, and stops when we reach the final chunk (91-100):
# Initialize a list to hold all our chunks final_result = [] # Start with the first chunk's starting number current_start = 1 # Loop until we've covered up to 100 while current_start <= 100: # Skip the 51-60 chunk entirely if current_start == 51: current_start = 61 continue # Generate a chunk of 10 consecutive numbers chunk = list(range(current_start, current_start + 10)) final_result.append(chunk) # Move to the next chunk's starting value current_start += 10 # Print to verify the output for chunk in final_result: print(chunk)
How This Works:
current_startkeeps track of where each chunk begins, starting at 1.- The loop runs as long as
current_startis ≤ 100 (since our last chunk ends at 100). - When we hit
current_start = 51, we jump straight to 61 to skip the unwanted chunk. range(current_start, current_start + 10)creates a sequence of 10 numbers (since range is left-closed, right-open).- After adding each chunk to
final_result, we incrementcurrent_startby 10 to get the next chunk's start.
If You Want to Use a Double Loop
You mentioned thinking about a double loop—here's how that would work (outer loop controls chunks, inner loop builds each element):
final_result = [] current_start = 1 while current_start <= 100: if current_start == 51: current_start = 61 continue chunk = [] # Inner loop to add 10 elements to the chunk for _ in range(10): chunk.append(current_start) current_start += 1 final_result.append(chunk) # Print the result for chunk in final_result: print(chunk)
This achieves the same outcome, but uses an inner loop to build each chunk element by element instead of using range directly.
Either of these approaches will generate exactly the sequence you need, no third-party libraries required!
内容的提问来源于stack exchange,提问作者Camue

