【问题标题】:How to do nested loop in python list如何在python列表中进行嵌套循环
【发布时间】:2021-09-26 17:25:09
【问题描述】:
operation = ['add','subs']
num_list1 = [[2,4],[7,4],[8,4]]

def calc(op, x,y):
    if op=='add':
        return x+y
    elif op =='subs':
        return x-y

def preview():
    result =[]
    for x,y in num_list1:
        for op in operation:
            result.append([op, calc(op,x,y)])    
    return result


result_preview = pd.DataFrame(preview())
result_preview

我得到的输出是:

  1. [添加,6]
  2. [子,-2]
  3. [添加,11]
  4. [subs, 3]
  5. [添加,12]
  6. [subs, 4]

但我希望输出如下:

  1. [加, 6, 11, 12]
  2. [subs, -2, 3, 4]

请帮帮我

【问题讨论】:

    标签: python loops arraylist data-structures nested-loops


    【解决方案1】:

    为什么不用定义calc() 函数就做一个单行理解:

    output = [[op] + [x + y if op == "add" else x - y for x, y in num_list1] for op in operation]
    

    然后你可以打印内部列表:

    for l in output:
       print(l)
    

    【讨论】:

    • 另外,我认为在 python 中,列表理解通常比 for 循环更快。这可以通过使用 %timeit 魔术函数来测试。
    • @BenWS 这通常是正确的,因为即使列表组合仍然执行字节码级别的循环,它们也不必在每次迭代时查找列表并调用 list.append()
    猜你喜欢
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2013-03-17
    • 2023-03-25
    相关资源
    最近更新 更多