-2
i = 0
numbers = []

while i < 6:
    print "At the top i is %d" % i
    numbers.append(i)

    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i


print "The numbers: "

for num in numbers:
    print num

如何for仅使用循环获得确切的输出。我尝试了一些事情,但它根本不会发生。有可能吗?

4

2 回答 2

1

最简单的代码直接翻译是:

#!/usr/bin/env python

i = 0
numbers = []

for j in xrange(6):
    print "At the top i is %d" % i
    numbers.append(i)

    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i


print "The numbers: "

for num in numbers:
    print num

list以这种方式构造 a时,列表推导通常是一种更好的方法:

#!/usr/bin/env python

numbers = [i for i in xrange(6)]

print "The numbers: "

for num in numbers:
    print num

在这种情况下,您的代码可以进一步简化:

#!/usr/bin/env python

print "The numbers: "
for num in xrange(6):
    print num
于 2013-11-10T06:18:32.677 回答
0

如果您只关心“精确输出”,那么:

numbers = []
for i in range(6):
    print("At the top i is %d" %i)
    numbers.append(i)
    print("Numbers now: ", numbers)
    print("At the bottom i is %d" %(i+1))
print("The numbers: ")
[print(num) for num in numbers]

蟒蛇3。

于 2013-11-10T06:17:47.083 回答