Python列表:使用For循环手动创建使用逗号分隔它们的元素

时间:2017-12-17 23:25:21

标签: python list for-loop elements

我想创建以下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

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