2013-07-22 93 views
1

我有一個這樣的名單:如何找到列表中特定元素的位置?

website = ['http://freshtutorial.com/install-xamp-ubuntu/', 'http://linuxg.net/how-to-install-xampp-on-ubuntu-13-04-12-10-12-04/', 'http://ubuntuforums.org/showthread.php?t=2149654', 'http://andyhat.co.uk/2012/07/installing-xampp-32bit-ubuntu-11-10-12-04/', 'http://askubuntu.com/questions/303068/error-with-tar-command-cannot-install-xampp-1-8-1-on-ubuntu-13-04', 'http://askubuntu.com/questions/73541/how-to-install-xampp'] 

我要搜索,如果下面的列表中包含的某些URL或沒有。

URL會格式爲:url = 'http://freshtutorial.com'

該網站是一個列表的第1個要素。因此,我想打印 而不是0

我想循環中的所有東西,以便如果沒有該網址的網站,它會再次動態生成列表並再次搜索該網站。

我已經這樣做了,現在高達:

for i in website: 
    if url in website: 
     print "True" 

我似乎無法打印的位置,敷在循環的一切。此外,使用regex還是if this in that語法更好。由於

回答

1

下面是完整的程序:

def search(li,ur): 
    for u in li: 
     if u.startswith(ur): 
      return li.index(u)+1   
    return 0 

def main(): 
    website = ['http://freshtutorial.com/install-xamp-ubuntu/', 'http://linuxg.net/how-to-install-xampp-on-ubuntu-13-04-12-10-12-04/', 'http://ubuntuforums.org/showthread.php?t=2149654', 'http://andyhat.co.uk/2012/07/installing-xampp-32bit-ubuntu-11-10-12-04/', 'http://askubuntu.com/questions/303068/error-with-tar-command-cannot-install-xampp-1-8-1-on-ubuntu-13-04', 'http://askubuntu.com/questions/73541/how-to-install-xampp'] 
    url = 'http://freshtutorial.com' 
    print search(website,url) 

if __name__ == '__main__': 
    main() 
2
for i, v in enumerate(website, 1): 
    if url in v: 
     print i 
+2

它不應該是'如果URL中v',實際查找http://freshtutorial.com在網站[0]? – jureslak

+0

我的錯。 :(謝謝。 – zhangyangyu

+2

Enumerate帶有一個可選的關鍵字參數「start」,它可以讓你從1開始索引:http://docs.python.org/2/library/functions.html – erewok

1

代碼 -

for i in range(0,len(website)): 
    current_url = website[i] 
    if url in current_url: 
     print i+1 

這是一個簡單的for循環。

相關問題