在python中使用for函数中的值时将代码与for函数分离

2024-04-23 10:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,标题很混乱:s

for x in frequency:
        alphab = [x]
        frequencies = [frequency[x]]
        print alphab, frequencies

如何在仍然使用来自for x in frequency:的输出的情况下将下面的代码与上面的代码分开?如果我运行这里的内容,将为x的每个值而不是整个字符串打开直方图。 如果我在下面缩进任何东西,如图所示,直方图也只对x的第一个值运行。 有没有任何可能的方法可以使用整个字符串而不必在for中缩进直方图函数

pos = np.arange(len(alphab))
width = 1.0     

ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(alphab)
plt.xlabel('Letter')
plt.ylabel('Absolute Frequency')
plt.title("Absolute Frequency of letters in text")
plt.bar(pos, frequencies, width, color='r')
plt.show()

Tags: 字符串代码inposforpltax直方图
2条回答

我想您应该在调用plot函数之前填充数组,例如

alphab = []
frequencies = []
for x in frequency:
        alphab.append(x)
        frequencies.append(frequency[x])

# .. some more code here ..
plt.bar(pos, frequencies, width, color='r')
def plotfreq(frequency, alphab):

    pos = np.arange(len(alphab))
    width = 1.0     

    ax = plt.axes()
    ax.set_xticks(pos + (width / 2))
    ax.set_xticklabels(alphab)
    plt.xlabel('Letter')
    plt.ylabel('Absolute Frequency')
    plt.title("Absolute Frequency of letters in text")
    plt.bar(pos, frequency, width, color='r')
    plt.show()

for x in frequencies:

    plotfreq(x, frequencies[x])

这是你要找的东西吗?你知道吗

相关问题 更多 >