python - 对不同变量执行相同功能的有效方法
问题描述
我正在努力使我的代码更高效。目前,我确实有两个函数在 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 新手,所以我知道这可能看起来很难看,并且可能有更好、更有效的方法来做到这一点。目前,它对我有用。但也许你对我有一些意见?
解决方案
您可以简单地将您希望处理的列表传递给函数
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])
推荐阅读
- c++ - 使用win32应用程序获取系统的文化信息
- python - Python BeautifulSoup:获取标签内的内容
- c# - 使用 C# 和 ASP.net MVC 通过 WFC 客户端向自己发送一封测试电子邮件
- python - 如何使界面与铸造一起使用
- delphi - Datasnap 服务器身份验证问题与用户凭据的远程数据库
- ios - Flutter 插件 didReceiveRemoteNotification 不起作用
- sql - 查询以查找完成预订还需要多少商品
- php - 刷新视图模板 CakePHP 事件系统
- java - 如何在 lambda 中返回值
- saml-2.0 - Saml2.0 和 Service Provider 请求的数据