問題描述
Python:遍歷列表但重複一些項目 (Python: Loop through list but repeat some of the items)
In Python, I am writing a script that will simulate a customer placing an order. It will consist of creating the order, adding lines to it, and then checking out. I am currently doing it with something like:
api = ['login', 'createOrder', 'scanBarCode', 'addLine', 'checkout']
for apiName in apiList:
#call API
I am designing this more as a framework so it would be easy to add new APIs in case things change. My design question is this: How can I code it so that I can call scanBarCode and addLine N number of times? Something like:
api = ['login', 'createOrder', 'scanBarCode', 'addLine', 'checkout']
numberOfLines = (random number)
for apiName in apiList:
#call API
#if API name is scanBarCode, repeat this and the next API numberOfLines times, then continue with the rest of the flow
參考解法
方法 1:
Something like the following should get you started:
import random
api = ['login', 'createOrder', 'scanBarCode', 'addLine', 'checkout']
numberOfLines = random.randint(1, 10) # replace 10 with your desired maximum
for apiName in api:
if apiName == 'scanBarCode':
for i in range(numberOfLines):
# call API and addLine
else:
# call API
方法 2:
With a loop using range or (preferably) xrange:
if apiName == 'scanBarCode':
for _ in xrange(numberOfLines):
{{ do stuff }}
(by Matt、Andrew Clark、Merbs)