一行代码的功能

时间:2014-08-08 06:21:49

标签: python

对于以下代码(用于在IPython中生成图形),if k in [0, len(n_trials) - 1] else None做了什么?

%matplotlib inline
from IPython.core.pylabtools import figsize
import numpy as np
from matplotlib import pyplot as plt
#total figure size
figsize(11, 9)

import scipy.stats as stats

dist = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0, 1, 100)

# For the already prepared, I'm using Binomial's conj. prior.
for k, N in enumerate(n_trials):
    sx = plt.subplot(len(n_trials) / 2, 2, k + 1)
    plt.xlabel("$p$, probability of heads") \
        if k in [0, len(n_trials) - 1] else None
    #Make the y label not appeared
    plt.setp(sx.get_yticklabels(), visible=False)
    heads = data[:N].sum()
    y = dist.pdf(x, 1 + heads, 1 + N - heads)
    plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads))
    plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4)
    plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1)

    leg = plt.legend()
    leg.get_frame().set_alpha(0.4)
    plt.autoscale(tight=True)


plt.suptitle("Bayesian updating of posterior probabilities",
             y=1.02,
             fontsize=14)

plt.tight_layout()

1 个答案:

答案 0 :(得分:5)

该代码在很多方面都具有误导性。正如评论中指出的那样,由于逃避反斜杠,你所询问的那一行是前一行的延续。它变成了:

plt.xlabel("$p$, probability of heads") if k in [0, len(n_trials) - 1] else None

这只是一种令人费解的写作方式:

if k == 0 or k == len(n_trials) - 1:
    plt.xlabel("$p$, probability of heads")

语法'True' if condition else 'False'Python's version of the ternary operator,但在这种情况下没有理由使用它。