我正在尝试使代码更高效。目前,我确实有两个函数在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的新手,所以我知道这看起来很难看,并且可能有更好,更有效的方法。目前,它对我有效。但是也许你有一些建议给我?
答案 0 :(得分:1)
您可以简单地将要处理的列表传递给该功能
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SplashScreenActivity" />
答案 1 :(得分:1)
def a():
print("a")
def b():
print("b")
switch = True
while True:
if switch:
a()
switch = False
elif not swith:
b()
switch = True
else:
print('Error')