将全局变量用作python中循环的两倍计数器

问题描述 投票:0回答:1

我正在尝试在for周期中使用全局变量x像计数器一样。我正在使用这些点,这些点的坐标保存在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 

for j in range(len(a)): #first cycle for making new plots 
    image = plt.imshow(image_file_name) #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() 

python python-3.x global-variables local-variables
1个回答
0
投票

我不确定您要达到的目标,但这可能有用。看这个answer

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()

© www.soinside.com 2019 - 2024. All rights reserved.