0

我有一个由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列表中,因此我需要一种方法来循环浏览该颜色列表。我怎么能那样做?

4

2 回答 2

7

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

>>> from itertools import cycle
>>> cols = cycle(["red", "green", "blue"])
>>> next(cols)
'red'
>>> next(cols)
'green'
>>> next(cols)
'blue'
>>> next(cols)
'red'
于 2013-10-14T02:34:13.137 回答
4

您可以使用模运算符

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])
于 2013-10-14T02:36:26.710 回答