繁体   English   中英

如何在python中迭代具有字符串值的整数

[英]How do I iterate over an integer that has string values in python

我从班级属性中获得电影名称和时间的列表。 我用以下方式显示了此列表:

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
if i in films[i].title:

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

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

但这会将2匹配到'... part 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)
    # ...

如果您将影片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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM