如何在 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
我得到的输出是:
- [添加,6]
- [潜艇,-2]
- [添加, 11]
- [潜艇,3]
- [添加, 12]
- [潜艇,4]
但我希望输出如下:
- [添加、6、11、12]
- [替补,-2、3、4]
请帮帮我
为什么不用定义 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)
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
我得到的输出是:
- [添加,6]
- [潜艇,-2]
- [添加, 11]
- [潜艇,3]
- [添加, 12]
- [潜艇,4]
但我希望输出如下:
- [添加、6、11、12]
- [替补,-2、3、4]
请帮帮我
为什么不用定义 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)