不断减去 - Python 3.X

时间:2015-12-07 19:19:27

标签: python python-3.x

我有一个像:

这样的元组
mytuple = (10,10)
mylist = []
mylist.append(mytuple)

我想从mytuple中x的每次迭代中减去1,直到只有0,以便mylist看起来像

[(10,10),(9,10),(8,10),(7,10),etc.,(0,10)]

我在想一个for循环,但我无法弄清楚如何获得这个输出。感谢。

3 个答案:

答案 0 :(得分:1)

mytuple = (10,10)
mylist = []
mylist.append(mytuple)
# store mytuple's first value
val = mytuple[0] 

# while val is greater than 0
while (val > 0):
    # subtract 1 from val
    val -= 1
    # generate tuple and add to list
    mylist.append((val,10))
print(mylist)

答案 1 :(得分:1)

尝试类似:

mytuple = (10,10)
mylist = [(i,mytuple[1]) for i in range(mytuple[0],-1,-1)]

答案 2 :(得分:0)

范围允许您指定迭代所采取的步骤,这使您可以执行以下操作:

mytuple = (10,10)
mylist = []
for i in range(mytuple[0], -1, -1):
    mylist.append((i, mytuple[1]))
print(mylist)

在此处查看此操作:http://ideone.com/wnM5zb