2016-09-11 4 views
-1

for 루프를 작성하여 세트의 사용자 데이터를 빠르게 얻습니다. 데이터를 유용하게 유지하려면 각 변수에 저장하는 변수가 있어야합니다. 지금까지 내가 가지고있는 것 :변수가 증가하는 루프의 경우

hey = ['11', '12', '13', '14'] 
x = 0 
for i in hey: 
    x += 1 
    showtimesx = raw_input('NOG >') 
    print showtimesx 

print "" 
print "Showtime at 11: " + showtimesx 
print "Showtime at 12: " + showtimesx 
print "Showtime at 13: " + showtimesx 
print "Showtime at 14: " + showtimesx 

마지막 인쇄물은 showtimesx의 가치가 증가했는지 확인하는 것입니다. 그러나, 내가 그것을 실행할 때마다, 그들 모두는 마지막으로 입력 된 값과 동일하게 끝납니다.

나는 x + = 1 행을 이동시키고, x = 0 라인을 루프 내부에 넣고 다른 일련의 것들을 시도했지만 아무 것도 작동하지 않았다.

어떻게 해결할 수 있습니까?

+2

당신이 코드의 그 선 사이에서 변경하는'showtimesx'의 가치를 일으킬 것이라고 생각하십니까? – hobbs

+2

프로그램을 작성하면 순서대로 문제가 발생합니다. 코드에서'showtimesx'에 대한 모든 변경 사항은 코드를 표시하기 전에 발생하며 단일 값을 저장합니다. 결과는 놀라운 것이 아닙니다. 힌트 :'hey'는 여러 값을 저장합니다. 아마도 비슷한 기술을 사용하여'showtimesx'에 여러 값을 저장할 수 있습니다. –

+0

당신은 아마 [사전] (http://www.tutorialspoint.com/python/python_dictionary.htm) – ti7

답변

0

당신은 목록을 사용하려면 :

hey = ['11', '12', '13', '14'] 
showtimes = [raw_input('NOG >') for i in hey] 

print "" 
print "Showtime at 11: " + showtimes[0] 
print "Showtime at 12: " + showtimes[1] 
print "Showtime at 13: " + showtimes[2] 
print "Showtime at 14: " + showtimes[3] 
+0

해결책을 가져 주셔서 감사합니다. 실제로 작동합니다! :) –

0

이유는 for가하는 각 루프, showtimesx 덮어 쓰기됩니다 있다는 것입니다. 이 코드 타격 데 도움이됩니다

hey = ['11', '12', '13', '14'] 
x = 0 
showtimesx = [] 
for n in hey : 
    for i in n: 
     x += 1 
     showtimesx.append(input('NOG >')) #Adds the user's input too end of showtimesx            
     print (showtimesx)    #FYI: input() is equal to raw_input() in python3 
     break 

print ("") 
print ("Showtime at 11: " + showtimesx[0]) 
print ("Showtime at 12: " + showtimesx[1]) 
print ("Showtime at 13: " + showtimesx[2]) 
print ("Showtime at 14: " + showtimesx[3]) 
0

목록 접근 당신이 반복하고 각 값으로 작업을 수행해야하는 경우, enumerate(), which will return both the value from your list and its position in the list을 시도

.
이렇게하면 색인의 값을 색인별로 변경할 수도 있습니다. 귀하의 경우에는

mylist = ['11', '12', '13', '14'] 

for index, value in enumerate(mylist): 
    if int(value) == 12: 
     mylist[index] = "fifteen instead" 

print mylist # ['11', 'fifteen instead', '13', '14'] 

사전 접근, consider using a dictionary. 이렇게하면 더 쉽게 저장할 수 있고 나중에 mylist[1]과 같은 일부 인덱스를 기억하거나 값을 찾을 때까지 검색하지 않고 나중에 이름 ("키")으로 다시 쿼리 할 수 ​​있습니다.

>>> colors = {"pineapples": "sorry, no pineapples"} # initial key: value pairs 
>>> colors["red"] = "#FF0000" # add value 
>>> print colors["red"] # retrieve a value by key 
#FF0000 

는 여기에 귀하의 케이스의 완성 기능으로 예입니다 :

def showtimes(list_of_times, display=True): 

    dict_of_times = {} # empty dictionary to store your value pairs 

    print "please enter values for the {} showtimes".format(len(list_of_times)) 
    for value in list_of_times: 
     dict_of_times[value] = raw_input("NOG > ") 

    if display: # Let the user decide to display or not 
     print "" 
     for time in sorted(dict_of_times.keys()): # dictionaries are unsorted 
      print "Showtimes at {}: {}".format(time, dict_of_times[time]) 

    return dict_of_times # keep your new dictionary for later 


hey = ['11', '12', '13', '14'] 
showtimes(hey) # pass a list to your function 

관련 문제