python-3.x 在一个列表中应用多个“for”

4si2a6ki  于 2023-02-10  发布在  Python
关注(0)|答案(1)|浏览(169)

我需要在一个列表中应用多个"for"来使用以前创建的列表。
我还需要将最后一个列表中的值四舍五入到第二位数,但有一个问题我不明白。
下面是部分代码:

koef_ob_dvig = 39
v_list = [0, 20, 40, 60, 80, 100, 120, 140, 160, 170]
n = [i * koef_ob_dvig for i in v_list]
Ne_list = [round((x / 3600 * mekh_kpd) * (G * koef_dor_sopr + k * F * (x ** 2) / 13), 2) for x in v_list]

n_tabl = [0, 20, 40, 60, 80, 100, 120]
Ne_tabl = [0, 20, 50, 73, 92, 100, 92]
n_graph = [round((max(n)/100 * x1), 2) for x1 in n_tabl]
Ne_graph = [round((max(Ne_list)/100 * x2), 2) for x2 in Ne_tabl]

#Further problems arise

Mk_tabl = [(30 * x3 / 3.14 for x3 in Ne_graph) / x4 for x4 in n_graph]

# This part works correctly (30 * x3 / 3.14 for x3 in Ne_graph)
# But when I try to divide each received element into the corresponding element of the n_graph list an error occurs
djp7away

djp7away1#

我不太清楚你的目标是什么,但我认为这是两件事之一。
暂时不考虑具体的计算,假设Mk_tab1变量的目标是对Ne_graph中的 * each * 元素和n_graph中的 * each * 元素执行计算:
即,使用以下示例数据:

#consider this basic example
#pretend that you wanted to just divide each element of Ne_graph by each element of n_graph:

Ne_graph = [a, b, c, d, e]
n_graph = [1,2,3,4,5]
...
Mk_tab1 = [a,b/2,c/3,d/4,e/5]

如果这就是你想要的,那么最好的方法就是创建一个函数,它接受两个长度相等的列表作为输入,运行一个for循环,并返回一个长度相同的列表以及所需的计算结果;就像这样:

def myfun(list1,list2):
  if len(list1) != len(list2):
    #throw error, do something else
  else:
    result = [list1[i] / list2[i] for i in range(len(list1))]
    return result

Mk_tab1 = myfun(Ne_graph,n_graph)

如果您实际想要的是对Ne_graph中的 * every * 元素和n_graph中的 * every * 元素进行计算:
例如:

#consider the same basic example
#if you wanted to operate on each element in one list with each element of the other list
#then the result would be a 2D list; meaning you need to list comp twice:

Ne_graph = [a,b,c,d,e]
n_graph = [1,2,3,4,5]
...
Mk_tab1 = [[a,b,c,d,e],
           [a/2,b/2,c/2,d/2,e/2],
           [a/3,b/3,c/3,d/3,e/3],
           [a/4,b/4,c/4,d/4,e/4],
           [a/5,b/5,c/5,d/5,e/5]]

那么可以这样来完成:

Mk_tab1 = [[x/y for x in Ne_graph] for y in n_graph]

相关问题