我想创建以下python列表:
[MIN_SPAN_1, MIN_SPAN_2, MIN_SPAN_3]
以下是我尝试的代码:
numbers_list = [1, 2, 3]
for i in numbers_list:
print(('MIN_SPAN' + '_' + str(i)))
下面是结果输出,你可以看到它并不是我想要的:
MIN_SPAN_1
MIN_SPAN_2
MIN_SPAN_3
答案 0 :(得分:3)
newlist = ["MIN_SPAN_{}".format(entry) for entry in numbers_list]
会使[“MIN_SPAN_1”,“MIN_SPAN_2”,“MIN_SPAN_3”]
或者您是否正在尝试打印阵列?
newlist = ["MIN_SPAN_{}".format(entry) for entry in numbers_list]
print(newlist)
打印输出:[“MIN_SPAN_1”,“MIN_SPAN_2”,“MIN_SPAN_3”]
答案 1 :(得分:0)
列表理解是@Micheal的一种方式。否则,如果您想要按照自己的方式尝试:(创建一个空列表并附加它)
numbers_list = [1, 2, 3]
new_list = []
for i in numbers_list:
new_list.append(('MIN_SPAN' + '_' + str(i)))
输出,
print(new_list)
>['MIN_SPAN_1', 'MIN_SPAN_2', 'MIN_SPAN_3']
答案 2 :(得分:0)
You can do without loop with just one line
numbers_list = [1, 2, 3]
print(list(map(lambda x:("MIN_SPAN_{}".format(x)),numbers_list)))
output:
['MIN_SPAN_1', 'MIN_SPAN_2', 'MIN_SPAN_3']