Python列表理解设置局部变量

时间:2015-08-19 14:25:00

标签: python python-2.7 list-comprehension

我在使用Python中的列表理解方面遇到了麻烦

基本上我的代码看起来像这样

output = []
for i, num in enumerate(test):
    loss_ = do something
    test_ = do something else
    output.append(sum(loss_*test_)/float(sum(loss_)))

我如何使用列表理解来编写它,例如:

[sum(loss_*test_)/float(sum(loss_))) for i, num in enumerate(test)]

但我不知道如何分配loss_test_

的值

3 个答案:

答案 0 :(得分:2)

您可以使用嵌套列表推导来定义这些值:

output = [sum(loss_*test_)/float(sum(loss_)) 
          for loss_, test_ in ((do something, do something else) 
                               for i, num in enumerate(test))]

当然,这是否更具可读性是另一个问题。

答案 1 :(得分:1)

正如雅罗斯拉夫在评论中提到的,列表推导不允许您直接将值保存到变量中。

然而,它允许您使用功能。

我已经制作了一个非常基本的示例(因为您提供的示例未完成测试),但它应该显示您仍然可以在列表解析中执行代码。

def loss():
    print "loss"
    return 1

def test():
    print "test"
    return 5

output = [loss()*test() for i in range(10) ]
print output

这种情况会导致列表[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

我希望以某种方式展示你如何能够最终得到你正在寻找的行为。

答案 2 :(得分:0)

ip_list = string.split(" ")                     # split the string to a list using space seperator

for i in range(len(ip_list)):                   # len(ip_list) returns the number of items in the list - 4 
                                                # range(4) resolved to 0, 1, 2, 3 

    if (i % 2 == 0): ip_list[i] += "-"          # if i is even number - concatenate hyphen to the current IP string 
    else: ip_list[i] += ","                     # otherwize concatenate comma

print("".join(ip_list)[:-1])                    # "".join(ip_list) - join the list back to a string
                                                # [:-1] trim the last character of the result (the extra comma)