首页 > 解决方案 > 对不同变量执行相同功能的有效方法

问题描述

我正在努力使我的代码更高效。目前,我确实有两个函数在 while 循环中执行基本相同的操作。只有主题(a和b)不同。这两个主题在每个循环中轮流进行。

到目前为止,这是我的框架:

#run engine
engine_running = True

#set first subject
a = True
b = False

# while engine is running rotate between a and b
while engine_running == True:
       if (a == True):
             Function_a()
             a = False
             b = True
       elif (b == True):
             Function_b()
             a = True
             b = False
       else:
             print('Error')       

这是两个功能的框架。值得注意的是,每个函数都读取同一组数据,其中包含 a 和 b 的数据。

def Function_a():
       import Data
       import random

       # Get Data and the weights
       List = [Data.a_person1, Data.a_person2, Data.a_person3]
       Weight = [List[0]['attribute'],List[1]['attribute'], List[2]['attribute']

       # Choosing a random person based on its attribute
       Selection = random.choices(List,Weight)
       print(Selection[0]['name'], 'has been chosen')
def Function_b():
       import Data
       import random

       # Get Data and the weights
       List = [Data.b_person1, Data.b_person2, Data.b_person3]
       Weight = [List[0]['attribute'],List[1]['attribute'], List[2]['attribute']

       # Choosing a random person based on its attribute
       Selection = random.choices(List,Weight)
       print(Selection[0]['name'], 'has been chosen')

我是 python 新手,所以我知道这可能看起来很难看,并且可能有更好、更有效的方法来做到这一点。目前,它对我有用。但也许你对我有一些意见?

标签: python

解决方案


您可以简单地将您希望处理的列表传递给函数

def Function(data):
       import random

       # Get Data and the weights
       Weight = [data[0]['attribute'], data[1]['attribute'], data[2]['attribute']

       # Choosing a random person based on its attribute
       Selection = random.choices(data,Weight)
       print(Selection[0]['name'], 'has been chosen')

Function([Data.a_person1, Data.a_person2, Data.a_person3])    
Function([Data.b_person1, Data.b_person2, Data.b_person3])

推荐阅读