如何在python中使用循环创建元组 [英] How to create tuple with a loop in python

查看:383
本文介绍了如何在python中使用循环创建元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建该元组:

a=(1,1,1),(2,2,2),(3,3,3),(4,4,4),(5,5,5),(6,6,6),(7,7,7),(8,8,8),(9,9,9)

我尝试过

a=1,1,1
for i in range (2,10):
    a=a,(i,i,i)

但是,每次迭代它都会在其他元组中创建一个元组.

However it creates a tuple inside other tuple in each iteration.

谢谢

推荐答案

在元组中使用一个逗号,然后加入:

Use an extra comma in your tuples, and just join:

a = ((1,1,1),)
for i in range(2,10):
    a = a + ((i,i,i),)

编辑:改编juanpa.arrivillaga的注释,如果您想坚持循环,这是正确的解决方案:

Edit: Adapting juanpa.arrivillaga's comment, if you want to stick with a loop, this is the right solution:

a = [(1,1,1)]
for i in range (2,10):
    a.append((i,i,i))
a = tuple(a)   

这篇关于如何在python中使用循环创建元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆