如何在Python三元运算符上换行? [英] How to make a line break on the Python ternary operator?

查看:629
本文介绍了如何在Python三元运算符上换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候在Python中包含三元运算符的行太长了:

answer = 'Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel."

是否存在使用三元运算符在79个字符处换行的推荐方法?我在 PEP 8 中找不到它.

解决方案

您始终可以扩展跨越多条物理线的逻辑线并带有括号:

answer = (
    'Ten for that? You must be mad!' if does_not_haggle(brian)
    else "It's worth ten if it's worth a shekel.")

这称为隐式联接. /p>

以上使用PEP8万能缩进一步式样式(称为

但这会使您更快地达到80列的最大值.

您将ifelse部分精确地放在什么位置;我在上面使用了我的个人喜好,但是对于运营商,尚没有任何人同意的特定样式.

Sometimes a line containing a ternary operator in Python gets too long:

answer = 'Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel."

Is there a recommended way to make a line break at 79 characters with a ternary operator? I did not find it in PEP 8.

解决方案

You can always extend a logical line across multiple physical lines with parentheses:

answer = (
    'Ten for that? You must be mad!' if does_not_haggle(brian)
    else "It's worth ten if it's worth a shekel.")

This is called implicit line joining.

The above uses the PEP8 everything-indented-one-step-more style (called a hanging indent). You can also indent extra lines to match the opening parenthesis:

answer = ('Ten for that? You must be mad!' if does_not_haggle(brian)
          else "It's worth ten if it's worth a shekel.")

but this leaves you hitting the 80-column maximum all the faster.

Where precisely you put the if and else portions is up to you; I used my personal preference above, but there is no specific style for the operator that anyone agrees on, yet.

这篇关于如何在Python三元运算符上换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆