简体   繁体   English

python3中的嵌套for循环:产生两个for循环的输出

[英]nested for loops in python3: produce an output of two for loops

I have this code我有这个代码

import numpy as np
import pandas as pd
from scipy.spatial import distance
mn= [(252, 468), (252, 495), (274, 481), (280, 458), (298, 479), (301, 458), (324, 499)]
name=['loc1','loc2','loc3','loc4','loc5','lco6','loc7']

zz= [(329, 478), (336, 455), (346, 499), (352, 478), (374, 468), (381, 499), (395, 459), (406, 488)]

L = pd.Series()
for name, i in list(zip(name, mn)):
    for e in zz:
        L[name] = distance.euclidean(e, i)
print(L)

w=100
dd = np.sqrt(np.power(L, 2) + np.power(w, 2))
print(dd)

Here is what it gives as an output for L & dd:这是它作为 L & dd 的输出给出的内容:

loc1    155.293271
loc2    154.159009
loc3    132.185476
loc4    129.522199
loc5    108.374351
lco6    109.201648
loc7     82.734515
dtype: float64
loc1    184.705170
loc2    183.752551
loc3    165.749811
loc4    163.633737
loc5    147.461859
lco6    148.070929
loc7    129.788289

my trouble that it only gives L&dd for one point in zz, but what I want to have L for each point in zz and then be able to use it to get dd for each value in L.我的麻烦是它只为 zz 中的一个点提供 L&dd,但是我想要为 zz 中的每个点提供 L,然后能够使用它为 L 中的每个值获取 dd。

Thanks for your help!谢谢你的帮助!

You are almost there.你快到了。 Basically you can replace your for loop with this:基本上你可以用这个替换你的 for 循环:

L = pd.Series()
for name, i in list(zip(name, mn)):
    j = [] # save the intermediary results here
    for e in zz:
        j.append(distance.euclidean(e, i)) 
    L[name] = j # append at once all computations are done

This will give you something like this:这会给你这样的东西:

loc1    [77.64663547121665, 85.0, 98.97979591815695, 1...
loc2    [78.85429601486528, 93.03762679690406, 94.0850...
loc3    [55.08175741568164, 67.23094525588644, 74.2159...
loc4    [52.92447448959697, 56.08029957123981, 77.6981...
loc5    [31.016124838541646, 44.94441010848846, 52.0, ...
lco6    [34.40930106817051, 35.12833614050059, 60.8769...
loc7    [21.587033144922902, 45.60701700396552, 22.0, ...

Next step, you can do make use of .apply functions:下一步,您可以使用.apply函数:

op = (L
     .apply(lambda x: np.sqrt(np.power(x, 2) + np.power(w, 2)))
     .apply(lambda x: x[0])) # get the first value of each array

loc1    126.605687
loc2    127.349912
loc3    114.166545
loc4    113.141504
loc5    104.699570
lco6    105.754433
loc7    102.303470
dtype: float64

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

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