一行退货条件

时间:2018-04-04 09:57:44

标签: python return conditional-statements

这是我的代码:

d = {'key1':1,'key2':5}

def pop1(d):
    return d.pop('key2') if len(d) > 1 else d

def pop2(d):
    if len(d) > 1: d.pop('key2')
    return d

def test(a):
    return a, len(a)

pop2工作正常:

print test(pop2(d))

({'key1': 1}, 1)

pop1没有:

print test(pop1(d))

TypeError: object of type 'int' has no len()

我错过了什么?是关于pop()函数还是单行条件?

2 个答案:

答案 0 :(得分:2)

如果我们分析以下return语句:

d.pop('key2') if len(d) > 1 else d

我们看到当字典的长度小于1时,只返回字典。这不是这种情况,因此我们对len(d)> 1时感兴趣。

在这种情况下,返回d.pop('key2')。从the documentation开始,我们看到.pop方法将:

  

如果密钥在字典中,请将其删除并返回其值

...所以pop1会返回'key2' 5的值。

由于len()是一个整数,因此当您调用5时会出现错误。

错误表明了这一点:

  

TypeError:'int'类型的对象没有len()

为什么pop2()有效?

这个函数不使用决定是返回值还是整个字典的三元组,而是总是返回d - 字典。

这意味着始终可以调用len()并按预期工作。

答案 1 :(得分:0)

当你这样做时:

library(tidyverse)
mtcars %>% 
    group_by(cyl) %>%
    summarise(Cosmpg = max(cos(mpg)), list(describe(mpg))) %>%
    unnest
# A tibble: 3 x 15
#    cyl Cosmpg  vars     n  mean    sd median trimmed   mad   min   max range   skew kurtosis    se
#  <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>    <dbl> <dbl>
#1  4.00  0.743  1.00 11.0   26.7  4.51   26.0    26.4  6.52  21.4  33.9 12.5   0.259   -1.65  1.36 
#2  6.00  0.939  1.00  7.00  19.7  1.45   19.7    19.7  1.93  17.8  21.4  3.60 -0.158   -1.91  0.549
#3  8.00  0.989  1.00 14.0   15.1  2.56   15.2    15.2  1.56  10.4  19.2  8.80 -0.363   -0.566 0.684

print test(pop1(d)) 将返回5

所以发表你的陈述pop1(d)

print(test(5)) - &gt; 5不是字符串,因此您将收到错误。

相关问题