使用数字序列格式化字符串以生成按 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)
您可以使用 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)]
我想要一个字符串列表:
[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)
您可以使用 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)]