Python random.choice([i if len(i)== 9 for i in words])列表理解上的语法错误

时间:2013-11-06 07:58:13

标签: python list list-comprehension

Python 2.7

Ubuntu 12.04

我试图改变这一点:

nine = []
for each in word_list:
    if len(each) == 9:
        nine.append(each)
return random.choice(nine)

进入这个:

return random.choice([i if len(i) == 9 for i in words])

然而,这给了我一个语法错误,我相信顺序是正确的,所以导致它失败的原因是什么?

3 个答案:

答案 0 :(得分:8)

如果你没有其他部分,if必须在最后。所以改变

[i if len(i) == 9 for i in words]

[i for i in words if len(i) == 9]

答案 1 :(得分:4)

使用过滤器(因为这就是你正在做的事情)

random.choice(filter(lambda x: len(x) == 9, words))

答案 2 :(得分:3)

当您使用条件语句/三元运算符时,您必须提供else:部分。尝试类似:

return random.choice([i if len(i) == 9 else '' for i in words])

当然,您可能有random.choice()返回一个空字符串的机会。如果您希望列表推导仅返回i 当且仅当长度为9时,您可以将条件放在列表推导的末尾,这将 not 需要else:

return random.choice([i for i in words if len(i) == 9])