循环浏览列表中的元素,为打印分配不同的颜色



我有一个由N子列表组成的主列表(这个数字会随着不同的运行而变化),每个子列表都包含成对的x,y点。我需要一种方法来用不同的颜色绘制这些子列表中的点,这些颜色取自元素(通常)比子列表少的列表。为此,我需要一种方法来循环浏览此颜色列表。这是我所追求的摘录:

# Main list which holds all my N sub-lists.
list_a = [[x,y pairs], [..], [..], [..], ..., [..]]
# Plot sub-lists with colors taken from this list. I need the for block below
# to cycle through this list.
col = ['red', 'darkgreen', 'blue', 'maroon','red']
for i, sub_list in enumerate(list_a):
    plt.scatter(sub_list[0], sub_list[1], marker='o', c=col[i])

如果len(col) < len(list_a)(大多数情况下都会发生),这将返回错误。由于对于给定的代码运行,子列表的数量会有所不同,因此我无法将许多颜色硬编码到col列表中,因此我需要一种方法来循环浏览该颜色列表。我该怎么做?

IIUC,你可以使用itertools.cycle,然后使用next代替c=col[i]。 例如:

>>> from itertools import cycle
>>> cols = cycle(["red", "green", "blue"])
>>> next(cols)
'red'
>>> next(cols)
'green'
>>> next(cols)
'blue'
>>> next(cols)
'red'

您可以使用取模运算符

numberOfColors = len(col)
for i, sub_list in enumerate(list_a):
    plt.scatter(sub_list[0], sub_list[1], marker='o', c=col[i % numberOfColors])

最新更新