Python:循环遍历列表,但重复一些项

2024-04-26 17:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我编写了一个脚本来模拟客户下订单。它将包括创建订单、向其中添加行,然后签出。我现在正在做这样的事情:

api = ['login', 'createOrder', 'scanBarCode', 'addLine', 'checkout']
for apiName in apiList:
  #call API

我把它设计成一个框架,这样在情况发生变化时添加新的api就很容易了。我的设计问题是:如何对它进行编码,以便可以多次调用scanBarCode和addLine?比如:

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

Tags: thein订单apiforlogincallcheckout
2条回答

使用range或(最好)xrange循环:

if apiName == 'scanBarCode':
    for _ in xrange(numberOfLines):
        {{ do stuff }}

应该从以下内容开始:

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

相关问题 更多 >