1

我有一个来自我的班级属性的电影标题和时间列表。我已经显示了这个列表:

for i in range(0, len(films)):
     print(i, films[i].title, films[i].time)

这给了我一个标题的数量和时间列表。

现在我想获取标题中的任何项目,以便我可以根据座位数的选择进行计算。

我试过这个:

i = int(input("Please select from our listings :"))
while i <= films[i].title:
    i = input("Please select from our listings :")
    if i in films[i].title:
        print("You have selected film: ",films[i].title)
        print("Regular seat: ", choice[regular], "\nVip Seat: ", choice[vip], "\nDiamond Seat: ", choice[diamond], "\nPlatinum Seat: ", choice[platinum], "\nDisability Regular Seat: ", disabilityRegular, "\nDisability Vip Seat: ", disabilityVip, "\nDisability Diamond Seat", disabilityDiamond, "\nDisability Platinum Seat", disabilityPlatinum )
        seatType = input("\nSelect your seat from these list: ")
        seating = int(input("How many seats: "))

        if seating == items in choice:
            total = seating*altogether[seatType]
            print(total) 

运行时显示如下:(注意列表从 0 开始):

29 End of Watch 20:00
30 Gremlins 19:30
31 The Twilight Saga: Breaking Dawn part 2 20:00

Please select from our listings :6
Please select from our listings :4

Traceback (most recent call last):
  File "C:/Python32/cin.py", line 91, in <module>
    if i in films[i].title:
TypeError: 'in <string>' requires string as left operand, not int
4

2 回答 2

1
if i in films[i].title:

尝试匹配字符串中的整数。您必须先将整数转换为字符串:

if str(i) in films[i].title:

但这会匹配2到名字之类'... part 2'的,而且也是'1492: Conquest of Paradise'

如果要查找电影的编号,请尝试以下操作:

for i, film in enumerate(films):
     print('{0:3} {1:30} {2:5}'.format(i, film.title, film.time))

while True:
    try:
        film = films[int(input("Please select from our listings :"))]
    except (ValueError, IndexError), e:
        # input is not an integer between 0 and len(films)
        continue

    # now we have a valid film from the list
    print("You have selected film: ",film.title)
    # ...
于 2012-12-07T10:13:19.653 回答
0

如果您使用电影 ID 作为键,则可能值得使用字典而不是列表来存储您的电影。这样您就可以使用“in”来检查您的电影 ID 键是否存在于字典中,而不必担心超出范围的异常。

class Film(object):
    def __init__(self, title, time):
        self.title = title
        self.time = time

films = {}
films[29] = Film("End of Days", "20:00")
films[30] = Film("Gremlins", "19:30")
films[31] = Film("The Twilight Saga: Breaking Dawn part 2", "20:30")

for k,v in films.iteritems():
    print (k, v.title, v.time)

while True:
    i = int(input("Please select from our listings:"))
    if i in films:
        print ("You have selected film: ", films[i].title)
        # select seat here
    else:
        continue
于 2012-12-07T11:05:19.680 回答