从其他列表创建新列表但精简

时间:2017-10-18 20:17:48

标签: python list file

我试图创建一个接收两位信息的函数,并根据文件中已存在的信息返回两个浮点列表:

让我们定义函数如下get_cakes_size_colour(),它应该接收两个字符串作为参数:文件名,Cake大小模式。该函数应返回一个列表,其中第一个元素是蛋糕大小列表,第二个元素是重量颜色列表。

这是我尝试的一些代码:

def get_dimer_distance_energy(file_name, weight_size):
    one_cake_size = True
    cake_size = []
    cake_colour = []
    cake_colours = []

    with open(file_name,'r') as file:
       for line in file:
          if cake_size in line.split() and one_cake_size:
              cake_size_1 = line.split()[1]
              cake_size_A = float(cake_size_1)
              cake_size_2 = line.split()[2]
              cake_size_B = float(cake_size_2)
              cake_size_3 = line.split()[3]
              cake_size_C = float(cake_size_3)

              one_cake_size=False

          elif cake_size in line.split() and not one_cake_size:
              cake_size_4 = line.split()[1]
              cake_size_D = float(cake_size_4)
              cake_size_5 = line.split()[2]
              cake_size_E = float(cake_size_5)
              cake_size_6 = line.split()[3]
              cake_size_F = float(cake_size_6)

          one_cake_size=True
          cake_size = cake_size +[average_size((cake_size_A), (cake_size_B), (cake_size_C), (cake_size_D), (cake_size_E), (cake_size_F))]
          return cake_size

          if "cake colour" in line:
             cake_colour += [line.split()[3]]
             return cake_colour
             for item in cake_colour:
                 cake_colours.append(float(item))
                 return cake_colours

我应该指出,我之前已经为average_size定义了一个完美的函数,如下所示:

def average_size(x1, y1, z1, x2, y2, z2):
    size = ( (x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2 )**0.5
    return size

运行此代码时发现了两个问题:

首先,我发现return函数没有返回列表,并且想知道是否有任何修改。我试图在网站上寻找解决方案,但找不到任何有用的解决方案。

其次,我发现在运行此代码时,它将返回average_size函数中的任何元素,而不是它将返回在赋值之前引用的局部变量。

0 个答案:

没有答案