python - 为什么在我只尝试分配变量时执行操作?
问题描述
我正在尝试重新组织以下代码
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.chart import XL_LABEL_POSITION
from pptx.util import Pt
prs = Presentation('test.pptx')
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_chart:
continue
chart = shape.chart
for series in chart.series:
for point, value in zip(series.points, series.values):
if value >= 7.5:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(0, 176, 80)
elif value < 7.5 and value >= 3.5:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 192, 0)
data_label = point.data_label
data_label.position = XL_LABEL_POSITION.CENTER
font = data_label.font
font.color.rgb = RGBColor(0, 0, 0)
font.size = Pt(9)
elif value <3.5 and value > 1:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 0, 0)
prs.save('testoutput.pptx')
进入以下代码
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.chart import XL_LABEL_POSITION
from pptx.util import Pt
prs = Presentation('test.pptx')
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_chart:
continue
chart = shape.chart
for series in chart.series:
for point, value in zip(series.points, series.values):
fill = point.format.fill
fill.solid()
data_label = point.data_label
font = data_label.font
if value >= 7.5:
fill.fore_color.rgb = RGBColor(0, 176, 80)
elif value < 7.5 and value >= 3.5:
fill.fore_color.rgb = RGBColor(255, 192, 0)
data_label.position = XL_LABEL_POSITION.CENTER
font.color.rgb = RGBColor(0, 0, 0)
font.size = Pt(9)
elif value <3.5 and value > 1:
fill.fore_color.rgb = RGBColor(255, 0, 0)
prs.save('testoutput.pptx')
其中变量被预先分配,然后在其余的 if 语句(填充、数据标签、字体)中使用。对我来说,代码中的一切看起来都不错,但我显然遗漏了一些东西,因为输出不同:
正在操作的原始幻灯片 (test.pptx)
代码1的正确输出:
代码 2 的输出不正确:
解决方案
也许与直觉相反,一个系列“点”(通常)在您访问它之前并不存在。因此,对点进行迭代是一种破坏性操作,因为某些图表标记(在本例中为条形)属性的继承被破坏了。
PowerPoint 通过在创建时将所有当前值分配给该点来解决此问题。在 UI 中,通过选择单个栏并对其进行编辑来创建一个点。
因此,您需要为您访问的每个点分配某些属性。您可以通过单独遍历值然后仅访问您将要更改的点来对此进行选择。
也许是这样的:
for idx, value in enumerate(series.values):
if value < 1:
continue
point = series.points[idx]
# --- do pointy operations ---
但是,一旦您访问该点,您就需要设置所有您不希望使用默认值的属性。
推荐阅读
- r - 将日期从 JSON 转换为 R 列表元素:“字符串不是标准的明确格式”
- r - Shiny 应用程序包未部署在 shinyapps.io 中
- javascript - 无法映射控制台中看到的对象的值
- wordpress - 我如何将 Whats App js 与静态 html 放在移动视图中
- php - 我想将具有自动循环索引的 PHP 数组的值返回到字符串中
- angular - 避免以角度创建对话框包装器组件
- vue.js - 在 Vuetify 数据表中使用 body 插槽时,no-data 和 no-results 不再起作用
- python - 在 matplotlib 图中显示从 0 到 100 的 y 轴
- python - Pandas ImportError:C 扩展:未构建名为“pandas._libs”的模块
- node.js - 如何用玩笑的 cookieJarSupport 模拟 axios