Python:创建带前缀的顺序列表的简便方法

标签 python

如何生成如下所示的字符串(或 Pandas 系列):

a1,a2,a3,a4,...,a19

下面的工作,但我想知道一个更短的方法

my_str = ""
for i in range(1, 20):
   comma = ',' if i!= 19 else ''
   my_str += "d" + str(i) + comma

最佳答案

您可以只使用列表理解来生成单个元素(使用字符串连接或 str.format ),然后 join分隔符字符串(逗号)上的结果列表:

>>> ['a{}'.format(i) for i in range(1, 20)]
['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19']
>>> ','.join(['a{}'.format(i) for i in range(1, 20)])
'a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19'

关于Python:创建带前缀的顺序列表的简便方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29339525/

相关文章:

Python:基于重叠项对DataFrame进行聚类

python - 在 Python Shell 中或直接运行 Python 文件

python - 'if x % 2 : return True' , 如果数字可以被 2 整除,那不会返回 True 吗?

python - Django 的 HttpRequest.META 字典是如何填充的?

python - 使用 hmac 生成瑞典 BankID Python 动画 QR 代码

python - 使用我自己的 gensalt() - 它足够安全吗?

python3 http.server 响应无效(Postman 和其他工具)

python - Facebook 广告 Python : How to access the HTTP header returned?

python - 如何将整数日期格式转换为 YYYYMMDD?

Python 类变量列表与 int 不一致的行为