简体   繁体   English

在 for 循环中的每次迭代中动态更改变量?

[英]Dynamically change the variable at each iteration in a for loop?

Given an arbitrary number of people:给定任意数量的人:

def __init__(self):
    self.person1 = ["Person_1", 0]
    self.person2 = ["Person_2", 0]
    ...

I would like to adjust the value "0" to "25".我想将值“0”调整为“25”。

How can I change the variable during each iteration so that I don't have to type it as follows:如何在每次迭代期间更改变量,以便我不必按如下方式键入它:

 def daily_income(self):
    self.person1[1] += 25
    self.person2[1] += 25
    ...

I tried to adjust the variable name by appending the "i" to the end of the variable name, however, it did not work.我试图通过将“i”附加到变量名称的末尾来调整变量名称,但是,它不起作用。

def daily_income(self):
    for i in range(1,3):
        'self.person_{}'.format(i)[1] += 25

This is not a good code design, but it can be done as follows:这不是一个好的代码设计,但可以按如下方式完成:

class People:
    def __init__(self):
        self.person1 = ["Person_1", 1]
        self.person2 = ["Person_1", 2]
        self.person3 = ["Person_1", 3]
        
    def daily_income(self):
        for i in range(1,4):
            attr = 'person{}'.format(i)
            val = getattr(self, attr)
            val[1] += 25
            setattr(self, attr, val) 

To get the variable, either follow this:要获取变量,请按照以下步骤操作:

def daily_income(self):
    for i in range(1,26):
        attr = f'person{i}'

or this: (as followed by bb1 )或者这个:(后面跟着bb1

def daily_income(self):
    for i in range(1,26):
        attr = 'person{}'.format(i)
        val = getattr(self, attr)
        val[1] += 25
        setattr(self, attr, val) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM