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

如何在for循环中根据数组元素值递增对应计数器变量?

Solution to Your Counter Increment Problem

First, let's break down why your current code isn't working: when you do len('array_{}'.format(i)), you're getting the length of the string "array_i" (like "array_0" has length 7) instead of the length of the actual array variable. You need to reference the array object itself, not its name as a string.

Here are two approaches to fix this:

Approach 1: Work with Your Existing Variable Names (Quick Fix)

If you can't restructure your arrays and counters into lists right now, you can use Python's globals() function to access variables by their string names. Here's how to adjust your code:

# Iterate over each array number
for i in range(567):
    # Get the actual array using its name
    current_array = globals()[f'array_{i}']
    # Loop through each element in the array
    for value in current_array:
        # Get the corresponding counter variable and increment it
        counter_name = f'counter_{value}'
        globals()[counter_name] += 1

Note: Using globals() can be error-prone if variable names are misspelled, but it works for your current setup.

A far better practice is to avoid having 567 separate array variables and 100 separate counter variables. Instead, store everything in lists—this makes your code more readable, easier to maintain, and faster to run.

Step 1: Collect all arrays into a single list

First, gather all your arrays into one list (you can do this once at the start of your code):

all_arrays = [array_0, array_1, array_2, ..., array_566]
# Pro tip: If you're creating these arrays programmatically, build this list directly instead of making separate variables!

Step 2: Use a list for counters instead of 100 variables

Replace your 100 counter_0 to counter_99 variables with a single list of 100 zeros:

counters = [0] * 100

Step 3: Loop through everything simply

Now your loop becomes straightforward and easy to follow:

for arr in all_arrays:
    for value in arr:
        # Increment the counter at index matching the element's value
        counters[value] += 1

Later, if you need to access the count for a specific value (like 90), just use counters[90] instead of counter_90.

Why Approach 2 is Better

  • Readability: No messy dynamic variable name juggling—everything is organized in structured lists.
  • Maintainability: If you add more arrays or adjust the value range, you don't have to rename dozens of variables.
  • Performance: Accessing list elements is faster than looking up variables in the global namespace.

内容的提问来源于stack exchange,提问作者L'recherche.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:46:47