2013-11-10 1 views
-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 루프 만 사용하여 정확한 출력을 얻으려면 어떻게해야합니까? 나는 몇 가지 일을 시도했지만 단순히 그렇게되지는 않습니다. 전혀 가능합니까?for 루프를 사용하는 중 Python의 While 루프 대신

+1

위의 예에서 들여 쓰기가 잘못되었습니다 ... – LotusUNSW

답변

1

간단한 직접 번역입니다 :이 경우

#!/usr/bin/env python 

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

print "The numbers: " 

for num in numbers: 
    print num 

:

#!/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을 구성, 지능형리스트은 종종 더 나은 방법입니다 코드를 더 단순화 할 수 있습니다.

#!/usr/bin/env python 

print "The numbers: " 
for num in xrange(6): 
    print num 
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] 

Python3. 코드의

+0

저는 Python 2를 사용하고 있습니다. 위 코드 중 어느 정도가 다른가요? –

+0

파이썬 2에서는 인쇄물 주위에 괄호가 없다는 것을 알고 있으며, 생성자 표현식에 대해서는 잘 모르겠습니다. 무엇이든, 당신은 처음에 인쇄 된 숫자 대신에 [print (num)] 대신에 사용했던 것을 사용할 수 있습니다. – TrustyHamster

관련 문제