如何打印列表中的剩余项?

2024-09-29 02:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在打印列表中剩余的项目。在

我想让用户输入他在哪里:乌得勒支(这是例如项目5,如果它匹配,打印列表中剩余的站点(例如:好的,第6项、第7项等是剩余的站点)。我试过切片,但这不是我真正想要的,或者我试错了。我可以使用哪个函数来执行此操作?在

到目前为止:

station = ['Utrecht', 'Amsterdam', 'Zwolle', 'Groningen','Leeuwarden']

vraag = input("Where are you?")
while station == vraag:

Tags: 项目函数用户列表input站点切片where
3条回答
location = input("Where are you? ")
try:
    if len(station[station.index(location)+1:]) == 0:
        print('This is the end.')
    print(' -> '.join(station[station.index(location)+1:]))
except ValueError:
    print('Check your location.')

输出:

^{pr2}$

首先,检查列表中是否存在该值,如果成功找到索引。在

最后,由于列表索引包含在“:”之前,所以应该使用(value+1)

try:
    print station[station.index(vraag)+1:]
except ValueError:
    print "Not in the list"

虽然我没有使用过3.4.3,但是在python3.4中,您可以使用一个普通的for循环来迭代它,因为它返回一个生成器。在

^{pr2}$

如何进行末端检查:

if lst == []:
    print "end"

这是密码。只需从用户输入中找到索引并使用切片

loc=input("Where are you?")
try:
    idx=station.index(loc)
    print(station[idx+1:])
except ValueError:
    pass

相关问题 更多 >