在我的代码中,我尝试用变量划分嵌套列表中的所有第二行。这样可以正常工作但它要求列表中每个项目的变量而不是一次。
这是我的代码:
nlist = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
def divide():
x = int(input('what is your divider?:'))
return x
nlist[1] = [num / divide() for num in nlist[1]]
print(nlist)
输出:
what is your divider?:5
what is your divider?:5
what is your divider?:5
what is your divider?:5
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]]
我想要的输出是什么:
what is your divider?:5
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]]
答案 0 :(得分:3)
nlist[1] = [num / divide() for num in nlist[1]]
每次都会调用 divide()
。使用
divide_value = divide()
nlist[1] = [num / divide_value for num in nlist[1]]
只调用一次并存储它。