首页 > 解决方案 > 在python中使用全局变量作为双倍循环的计数器

问题描述

我正在尝试x在我的 for 循环中使用像计数器这样的全局变量。我正在使用这些点,这些坐标保存在 col_values_X_right 和 col_values_Y_right 变量中——坐标列表。我尝试使用它们创建 15 个不同的图,因为在每个坐标列表中都存在分隔符“-”,它表示新数据章节的开始(从另一个来源获得)。这只是一个解释,我想使用这个代码。正如我之前所说,问题在于我不能循环使用我的全局计数器变量。我尝试使用global x,但我真的不明白它应该如何工作。当我尝试运行此代码时,它向我显示此错误SyntaxError: name 'x' is assigned to before global declaration。请帮帮我,我该如何修复它并在所有周期中使用 x 变量

x = 0

for j in range(number_of_separatores//2):
    image_plot1 = plt.imshow(image1)
    global x
    for i in range(len(col_values_X_right)-x):
        if stimulus_name[x+1] == '5_01.jpg' and col_values_X_right[x+1] != '-':
                plt.scatter([col_values_X_right[x+1]], [col_values_Y_right[x+1]])
                x += 1
        else:
            break
plt.show()

我对这个问题的补充:

x = 0 # the variable, that I want to use as a counter in my cycles 
a = 15
image = mpl.image.imread('file_name.png')
X = list() #put your float numbers here
Y = list() #and here

for j in range(a): #first cycle for making new plots 
    image_plot = plt.imshow(image) #the image on that I want to make my plot
    for i in range(len(X)): #columns of all coordinate that I will separate for differents plots by '-' symbol in it
        if X[x+1] != '-':
            plt.scatter([X[x+1], Y[x+1]) #one point on the plot, the length of X and Y is similar 
            x+=1 #for use next cell of the column on the next iteration of the cycle
        else:
            break #if I find the '-' symbol in column I want to end this plot end start next one. And here is a problem: I want to start from the last x cell, but if I ran this code, after first plot the x value reset and code plotting similar picture 


plt.show() 

标签: pythonpython-3.xglobal-variableslocal-variables

解决方案


我不太确定您要达到什么目标,但这可能会奏效。看看这个答案

x = 0 #Global

def foo():
    global x
    for j in range(10):
        for i in range(10 - x):
            #Do your own thing here
            if j % 2 == 0:
                x += 1
            else:
                break
    print("Inside: ", x)

def main():
    print("Before", x)
    foo()
    print("After", x)    

main()


推荐阅读