简体   繁体   English

如何使用 python 循环为图形生成标题序列

[英]How to use python loop to generate sequence of titles for figures

If I want to generate a sequence of strings "layer 1", "layer 2", .... , "layer n" , to use as the titles for my figures, is there an easy way to do this task by using a loop?如果我想生成一系列字符串"layer 1", "layer 2", .... , "layer n"来用作我的图形的标题,有没有一种简单的方法可以通过使用环形?

Thank you,谢谢,

Use formatted string literals or "f-strings" for short:使用格式化的字符串文字或简称“f-strings”:

def label_yielder(n):
    for i in range(1,n+1):
        yield(f"label {i}")

# print them out
for x in label_yielder(5): 
    print(x)

# store them in a list
labels = [x for x  in label_yielder(5)]

Of course, if you're using a for loop for plotting already, you can use f-string directly in the plot call (I'll assume you're using matplotlib.pyplot , should hold for most of the other libraries as well):当然,如果您已经使用for循环进行绘图,则可以直接在 plot 调用中使用 f-string(我假设您正在使用matplotlib.pyplot ,也应该适用于大多数其他库) :

import matplotlib.pyplot as plt
from numpy.random import randint

for x in range(5):
    data = randint(low=1,high=10, size=(10,))
    plt.plot(range(10), data, label=f"label{x+1}")
    plt.legend()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM