用于增加变量的循环

时间:2016-09-11 19:13:08

标签: python

我正在写一个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行以及其他一系列内容,但它们都不起作用。

我该如何解决?

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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])

答案 2 :(得分:0)

列表方法

如果您必须遍历a并对每个值执行操作,请尝试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
相关问题