遍历列表中的元素以指定不同的颜色以进行绘图

Gab*_*iel 0 python list matplotlib

我有一个由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])
Run Code Online (Sandbox Code Playgroud)

如果len(col) < len(list_a)(大部分时间都会发生),这将返回错误.因为对于给定的代码运行,子列表的数量会有所不同,我不能将多种颜色硬编码到col列表中,所以我需要一种循环遍历该颜色列表的方法.我怎么能这样做?

DSM*_*DSM 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'
Run Code Online (Sandbox Code Playgroud)