如何创建函数为股票列表设置对应起始索引的Range?
Got it, let's work through this. The core issue here is that your original function uses a fixed starting point (0) for its range, but you need each stock list to map to a unique starting index (0, 250, 500, etc.). The simplest fix is to add a parameter to your function that accepts this starting index, then use it to calculate the actual global position of each element in your stock list.
Step 1: Update the Function with a New Parameter
Here's how you can modify your pTrend function. We'll add a start_index parameter, then compute the global index for each element by adding the list's internal position to this starting value:
def pTrend(stock, start_index): pTrend = [] # Iterate over each position in the stock list for x in range(len(stock)): # Calculate the global index that matches your desired range start global_index = start_index + x # Use the global index for your conditions if global_index > 0: print('This') # Quick note: If your start_index is 0 or higher, global_index will never be <0—you might want to adjust this condition! if global_index < 0: print('That') # Add your logic to populate the pTrend list here, e.g.: # pTrend.append(your_calculation_based_on_global_index) return pTrend
For a cleaner approach, use enumerate to get both the internal index and the stock item directly:
def pTrend(stock, start_index): pTrend = [] for internal_idx, stock_item in enumerate(stock): global_index = start_index + internal_idx if global_index > 0: print('This') if global_index < 0: print('That') # Process the stock_item and build your pTrend list as needed return pTrend
Step 2: Call the Function with the Correct Starting Index
Now when you process each stock list, just pass its corresponding starting index:
# First stock list (maps to range 0 to 250) stock_list_1 = [...] # Your first dataset pTrend(stock_list_1, start_index=0) # Second stock list (maps to range 250 to 500) stock_list_2 = [...] # Your second dataset pTrend(stock_list_2, start_index=250) # Third stock list (maps to range 500 to 750) stock_list_3 = [...] # Your third dataset pTrend(stock_list_3, start_index=500)
Bonus: Batch Process Multiple Stock Lists Automatically
If you have all your stock lists in a single parent list, you can automate the starting index calculation (since each is 250 apart):
all_stock_lists = [stock_list_1, stock_list_2, stock_list_3, ...] for list_num, stock in enumerate(all_stock_lists): start_idx = list_num * 250 pTrend(stock, start_idx)
This way you don't have to manually track and pass the starting index for each list—let the loop handle the heavy lifting!
内容的提问来源于stack exchange,提问作者PyPro

