[英]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:我得到的输出是:
But I want the output to be like:但我希望输出是这样的:
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.