python - 避免Python中的冗余循环

标签 python loops for-loop python-itertools

我有两个列表(商品,销售),对于两个列表之间的每对商品、销售元素,我必须调用一个函数。我正在寻找一种Python式的方法来避免这种冗余循环

第一个循环:

# Create item_sales_list

item_sales_list = list()

for item,sales in itertools.product(items,sales):
  if sales > 100:
    item_sales_list.append([item,sales])

result = some_func_1(item_sales_list)

第二个循环:

# Call a function with the result returned from first function (some_func_1)


for item,sales in itertools.product(items,sales):
   some_func_2(item,sales,result)

最佳答案

至少如果将结果存储在列表中,并在 some_func_1 的调用站点添加条件,则至少可以避免对 itertools.product 的第二次调用:

item_sales_list = list(itertools.product(items, sales))

result = some_func_1([el for el in item_sales_list if el[1] > 100])

for item, sales in item_sales_list:
    some_func_2(item, sales, result)

除非您可以将 result 的不完整版本传递给 some_func_2,否则不可能一次性完成此操作。

关于python - 避免Python中的冗余循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57295954/

相关文章:

python - 使用 MongoEngine 在 Flask 中测试套件

python - 使用循环动态查找序数 : find th - st - nd - rd

for-loop - Go中使用 "continue Label"和使用 "break"跳出内循环的区别

swift - Xcode 9.4.1 - 如何跳过组的剩余部分并移至下一组

python - 评估 df 的每一行中的日期时间函数是否落在另一个 df 的日期时间范围内

Python urllib3 太多重定向

Python - 开发 Web 应用程序

python - 将日志文件解析为其嵌套的开始和结束对的算法/Python

c - 循环一个 Const Char

c - 使用 getchar() 时的额外循环和 getchar() 的行为