简体   繁体   English

如何在python列表中进行嵌套循环

[英]How to do nested loop in python list

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

And The output I get is:我得到的输出是:

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

But I want the output to be like:但我希望输出是这样的:

  1. [add, 6, 11, 12] [添加,6、11、12]
  2. [subs, -2, 3, 4] [潜艇,-2, 3, 4]

Please help me请帮我

Why don't you do a one-liner comprehension without even having to define a calc() function:为什么不用定义calc()函数就进行单行理解:

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

Then you can print the inner lists:然后你可以打印内部列表:

for l in output:
   print(l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM