0

我希望它要求用户输入他们最喜欢的电影,并将该输入添加到列表的末尾,然后再次显示列表。以及确保进入的电影至少还没有。这是我达到了多远:

films = ["Star Wars", "Lord of the Rings", "Shawshank Redemption", "God father"]

for films in films:
    print ("%s" % films)

add = input("Please enter a film: ")
films.insert(-1,add)
print (films)

编辑:

当我尝试时,我得到一个错误:

回溯(最近一次通话最后):

文件“H:\Modules (Year 2)\Advanced Programming\Python\Week 2 - Review and Arrays\Week 2.2 - Exercises.py”,第 48 行,在films.append(add) AttributeError: 'str' object has no attribute '附加'

4

4 回答 4

3

用于in检查该项目是否已存在于列表中,然后用于list.append将该项目添加到列表的末尾。

add = input("Please enter a film: ")
if add not in films:
    films.append(add)

请注意,在您已替换films为字符串的 for 循环中,请使用其他变量名称:

for film in films:
    print ("%s" % film)
于 2013-09-27T18:48:10.633 回答
1

错误在这里:

for films in films:
    print("%s" % films)

你正在做for films in films而不是for film in films.

此外,其他人认为更好的写作方式是正确films.insert(-1, ...)films.append(...)

于 2013-09-27T18:55:56.097 回答
0
"""
This is for a dictionary
""""
Cities={"London":0,"Cairo":2182,"Lagos":3110,"Lima":6314}
while True:
    city=input("Enter a city")
    if city in Cities:
        print (Cities[city])
    else:
        print("Not in dictionary please input the distance")
        distance=input()
        Cities[city]=int(distance)
        print (Cities)
于 2014-11-04T11:22:57.823 回答
0

检查它是否已经在列表中not in并用于append将其添加到列表的末尾:

films = ["Star Wars", "Lord of the Rings", "Shawshank Redemption", "God father"]

for films in films:
    print ("%s" % films)

add = input("Please enter a film: ")
if add not in films: films.append(add)
else: print("Already in list!")
print (films)
于 2013-09-27T18:49:22.637 回答