Python循环中向列表添加元素及Excel数据列表构建问题
Hey there, let's tackle your two Python questions one by one:
Adding elements to a list during a loop is straightforward with Python's built-in list methods. Here are the most common approaches:
Use the
append()method: This adds a single element to the end of the list every time you call it.my_list = [] for num in range(1, 6): my_list.append(num) print(my_list) # Output: [1, 2, 3, 4, 5]Use
extend()if you need to add multiple elements at once: This method takes an iterable (like another list) and adds all its elements to your list.my_list = [1, 2] my_list.extend([3, 4, 5]) print(my_list) # Output: [1, 2, 3, 4, 5]For a more concise, Pythonic approach, use a list comprehension: This lets you build the list in one line without explicit loop syntax.
my_list = [num for num in range(1, 6)]
The issue with your current code is that every loop iteration creates a new nested tuple—you're taking the existing follow (which becomes a tuple after the first iteration) and pairing it with the next element, leading to that layered structure.
Here are three fixes to get a flat tuple:
Method 1: Build a list first, then convert to tuple
Lists are designed for dynamic appending, so this is the most intuitive approach:
# Start with the first element in a list follow_list = [data2[1][2]] # Loop through the remaining indices for q in range(2, targets): follow_list.append(data2[q][2]) # Convert the list to a flat tuple follow = tuple(follow_list)
Method 2: Tuple concatenation
If you prefer working directly with tuples, make sure to initialize a tuple and concatenate with single-element tuples each time:
# Initialize as a single-element tuple (note the trailing comma!) follow = (data2[1][2],) for q in range(2, targets): # Concatenate with another single-element tuple follow += (data2[q][2],)
The trailing comma is crucial here—without it, you're just working with a single value, not a tuple.
Method 3: Generator expression (most concise)
Skip the explicit loop entirely with a generator expression wrapped in tuple():
follow = tuple(data2[q][2] for q in range(1, targets))
This iterates over all indices from 1 to targets-1, collects the elements, and converts them directly into a flat tuple in one line.
内容的提问来源于stack exchange,提问作者Oliver Smith

