簡體   English   中英

如何打印列表中的剩余項目?

[英]How to print remaining items in list?

我正在嘗試將剩余項目打印在列表中。

我想請用戶輸入他的位置:烏得勒支(例如,第5項,如果與之匹配,則打印列表中的其余停靠點(例如:好的,第6項,第7項等是剩余的停靠點)。嘗試切片,但這不是我真正想要的,或者我試錯了,我可以使用哪個功能?

到目前為止:

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

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

首先,檢查該值是否存在於列表中,如果成功,則找到索引。

最后,由於列表索引包含在“:”之前,因此您應該使用(value + 1)

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

雖然我還沒有使用3.4.3,但是在python 3.4中,您可以使用普通的for循環來迭代它,因為它會返回一個生成器。

lst = station[station.index(vraag)+1:]
for i in lst:
    print i,

如何做結束檢查:

if lst == []:
    print "end"
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.')

輸出:

location = 'Amsterdam'
'Zwolle -> Groningen -> Leeuwarden'

這是代碼。 只需從用戶輸入中找到索引並使用切片

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM