繁体   English   中英

使用数字序列格式化字符串以生成按Python中数字顺序排列的字符串列表

[英]Formatting strings with numeric sequences to generate a list of strings ordered by the numbers in Python

我想要一个字符串列表:

[2000q1, 2000q2, 2000q3, 2000q4,
 2001q1, 2001q2, 2001q3, 2001q4,
 2002q1, 2002q2, 2002q3, 2002q4 ...]

等等。

我想通过str.format在上面的Python中创建结果。

以下是我尝试的方法:

import numpy as np
x = list(range(2000, 2003))
x = np.repeat(x, 4)
y = [1,2,3,4] * 3

"{}q{}".format(x,y)
# One string containing all numbers (FAILED)

"{x[i for i in x]}q{y[j for j in y]}".format(**{"x": x, "y": y})
# IndexError (FAILED)

最后,我通过以下方法解决了问题:

result = list()
for i in range(0, len(y)):
    result.append("{}q{}".format(x[i],y[i]))
result

是否还有其他不需要显式循环的优雅解决方案? 我正在R中寻找类似的东西:

sprintf("%dq%d", x, y)

您可以使用嵌套列表理解:

result = ['{}q{}'.format(y, q+1) for y in range(2000, 2003) for q in range(4)]

您可以将map用作实用的解决方案,尽管方法要丑陋得多:

import itertools
final_data = list(itertools.chain(*map(lambda x:map(lambda y:"{}q{}".format(x, y), range(1, 5)), range(2000, 2003))))

输出:

['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3', '2001q4', '2002q1', '2002q2', '2002q3', '2002q4']

暂无
暂无

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

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