我试图在循环中找到最后一次迭代,以便我可以跳过它。这并不理想我不知道,但我的问题是分开的。
我是python的新手,但如果我没有弄错的话,这个for循环就是解压变量letter
。这使得for循环的第二次运行为空或在某种意义上被破坏。如果我的理解无论如何都是错误的,请随意评论或编辑。
this_iteration = 0
for [x, y, dx, dy, r], letter in letters_positions:
last_iteration = this_iteration
this_iteration += 1
this_iteration = 0
for [x, y, dx, dy, r], letter in letters_positions:
if this_iteration == last_iteration:
continue
this_iteration += 1
我尝试在第二个for循环中未成功传递,但第二个for循环仍未运行。
for letter in letters_positions:
有没有办法让我在第二次循环中重新包装变量?
更新:这是CairoSVG,不是我自己的代码,但我会尽力发布更多上下文。 letters_positions取自svg文件。我的代码之前的重要两行是以下内容。
from .helpers import distance, normalize, point_angle, zip_letters
letters_positions = zip_letters(x, y, dx, dy, rotate, node.text)
原始的CairoSVG代码可以在github上找到。
https://github.com/Kozea/CairoSVG/blob/master/cairosvg/text.py
答案 0 :(得分:2)
编辑(示例):
this_iteration = 0
letters_positions = list(letters_positions)
for [x, y, dx, dy, r], letter in letters_positions:
last_iteration = this_iteration
this_iteration += 1
this_iteration = 0
for [x, y, dx, dy, r], letter in letters_positions:
if this_iteration == last_iteration:
continue
this_iteration += 1
来自您发布的github link中的helpers.py
:
# Incidentally, they say that this method returns a list with the current letter's positions.
# This isn't true - it is returning a generator.
# To return a list, the outermost parenthesis need to be replaced with square brackets,
# or by simply adding list before the parenthesis
# i.e. [...] or list(...)
def zip_letters(xl, yl, dxl, dyl, rl, word):
"""Returns a list with the current letter's positions (x, y and rotation).
E.g.: for letter 'L' with positions x = 10, y = 20 and rotation = 30:
>>> [[10, 20, 30], 'L']
Store the last value of each position and pop the first one in order to
avoid setting an x,y or rotation value that have already been used.
"""
# Notice the parenthesis below - this is a generator that gets exhausted after one iteration
return (
([pl.pop(0) if pl else None for pl in (xl, yl, dxl, dyl, rl)], char)
for char in word)
因此,在第一次迭代后将其清空。从中创建一个列表或其他一些数据结构letters_positions = list(letters_positions)
,然后您可以多次循环它。
答案 1 :(得分:0)
letters_positions
是一个序列。如果您不想迭代最终元素,请迭代letters_positions[:-1]
编辑:如果您使用的是Python3,则可能需要先在list
上致电letters_positions