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

2024-04-20 01:03:32 发布

您现在位置: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)

Tags: 字符串inimportnumpyformat列表foras
2条回答

您可以使用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']

可以使用嵌套列表:

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

相关问题 更多 >