本文介绍了创建一个附加连续数字的字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信一定有一种简单的方法可以做到这一点:我想创建一个列表,该列表最终将成为 DataFrame 的列名.将有 13 列,每列代表一个时间段,称为Period n",其中 n 是时间段编号.我认为可能有一种方法可以通过循环构建此列表,但我将展示我尝试做的事情:

I'm sure there must e an easy way to do this: I want to create a list which will eventually become column names for a DataFrame. There will be 13 columns, each representing a period in time, called "Period n", where n is the period number. I think there's probably a way to build this list via loop, but I will show what I tried to do:

col_no = list(range(1,14))
col_name = ['Period' for n in range (1,14)]
col_list = col_name + col_no

print(col_list)

['Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13]

然后我尝试:

col_list = list(zip(col_name + col_no))
print(col_list)

[('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 (1,),
 (2,),
 (3,),
 (4,),
 (5,),
 (6,),
 (7,),
 (8,),
 (9,),
 (10,),
 (11,),
 (12,),
 (13,)]

基本上,我只想要一个容易生成的列表,上面写着Period 1"、Period 2"等.我对 Python 很陌生,而且很困惑.提前致谢

Basically, I just wanted an easily generated list that reads "Period 1", "Period 2", etc. I'm pretty new to Python, and pretty stumped.Thanks in advance

推荐答案

您可以在循环迭代时将它们(数字和单词 Period)连接在一起.

You can concatenate them (the number and the word Period) together while the loop iterates.

print([f'Period {i}' for i in range(1, 14)])

Python 2.7+

print(['Period {}'.format(i) for i in range(1, 14)])

这篇关于创建一个附加连续数字的字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:59