Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用数字序列格式化字符串,以生成Python中按数字排序的字符串列表_Python_String_String Formatting - Fatal编程技术网

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

使用数字序列格式化字符串,以生成Python中按数字排序的字符串列表,python,string,string-formatting,Python,String,String Formatting,我想要一个字符串列表,它是: [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 "{}

我想要一个字符串列表,它是:

[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']

您可以将
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)]

您可以使用嵌套列表:

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