我有一个电影片名列表和来自班级属性的时间。我已将此列表显示为:
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
答案 0 :(得分: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)
# ...
答案 1 :(得分: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