我想要一个字符串列表:
[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
作为一个功能性的解决方案,尽管它要丑陋得多:输出:
可以使用嵌套列表:
相关问题 更多 >
编程相关推荐