如何从可操作的循环中获得列表形式的打印输出?或者不打印就得到相同的结果?

时间:2019-01-24 19:56:05

标签: python python-3.x list

我有十张名为t1,... t10的表。我想将变量用于表名。代码是:

for i in range(1,11):
    print("t",i, sep='', end=', ')

 Output is: t1, t2, t3, t4, t5, t6, t7, t8, t9, t10,
 I will use like this: im.execute("delete from ' + b[1] + '"). So,
 I need a list b=["t1", "t2", ..... "t10"]

如何获得此输出列表?

2 个答案:

答案 0 :(得分:1)

您可以使用具有类似逻辑的列表理解来生成您要查找的列表。

例如:

items = [f't{i}' for i in range(1,11)]
print(items)
# OUTPUT
# ['t1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9', 't10']

# You could also do ['t{}'.format(i) for i in range(1,11)] if you are pre python 3.6

答案 1 :(得分:0)

ts = []
for i in range(1, 11):
    ts.append('t{}'.format(i))

或者,一行:

ts = ['t{}'.format(i) for i in range(1, 11)]