python - 一个 Python one liner?如果 x 在 y 中,则执行 x

标签 python ruby

numbers = [1,2,3,4,5,6,7,8,9]
number = 1

我可以在一行中写下以下内容吗?

if number in numbers:
    print number

使用ruby的风格:

puts number if numbers.include?(number)

我试过:

print number if number in numbers

但语法无效。

最佳答案

Python就是Python,Ruby就是Ruby。我的建议是不要尝试将一个写成另一个。

Python 没有 Ruby 的/Perl 的“后缀 if”,而编写它的 Pythonic 方式是您已经拥有的。

但如果你真的必须这样做,这会起作用:

if number in numbers: print number

违反官方风格指南,PEP8 , 虽然:

  • Compound statements (multiple statements on the same line) are generally discouraged.

    Yes:

    if foo == 'blah':
        do_blah_thing()
    do_one()
    do_two()
    do_three()
    

    Rather not:

    if foo == 'blah': do_blah_thing()
    do_one(); do_two(); do_three()
    

关于python - 一个 Python one liner?如果 x 在 y 中,则执行 x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9344345/

相关文章:

ruby - Ruby 变量和关键字的 Sublime 颜色语法

ruby - Ruby 的 put 和 write 方法有什么区别?

python - Pymongo 批量插入

python - Lambda + Python + 退出代码

android - 无法向上滚动

ruby - 有没有办法避免在 'elsif' 分支中多次调用函数?

ruby-on-rails - rails api 和 node.js 应用程序之间的用户身份验证

python - 如何防止小部件重叠?

python - 如何使用 keras image_ocr 示例预测 OCR 的结果?

ruby - 如何将数学运算(例如 +、-、*、/)作为参数传递给方法