2016-10-01 39 views
-2
ip = a list of ips 
ipf = list(filter(lambda x: x if not x.startswith(str(range(257,311))) else None, ip)) 

可以做這樣的事情嗎?我測試了它,它不起作用。 我想刪除從「ip」列表中以256. 257. 258. ecc ...爲310開頭的所有ips。Startswith用一個數字範圍代替一個單位

+1

有效的IP的部分將在0到255的範圍內(包括兩端)。 – thefourtheye

回答

3

不,str.startswith()不包含範圍。

您必須解析出第一部分並將其作爲整數進行測試;過濾也更容易與列表理解來完成:

[ip for ip in ip_addresses if 257 <= int(ip.partition('.')[0]) <= 310] 

另一種方法是使用ipaddress library;它會迴應一個ipaddress.AddressValueError例外任何無效的地址,因爲這超過255個與任何起始地址是無效的,你可以很容易地增選是過濾掉你的無效地址:

import ipaddress 

def valid_ip(ip): 
    try: 
     ipaddress.IPv4Address(ip) 
    except ipaddress.AddressValueError: 
     return False 
    else: 
     return True 

[ip for ip in ip_addresses if valid_ip(ip)] 
+0

所以在我的情況下,我需要使用:ipf = [x for ip in ip if 257 <= int(x.partition('。')[0])<= 310] right? – CatchJoul

+0

@Thavivelball:是的;我將'ip'重命名爲'ip_addresses'以使用更清晰的變量名稱。 –

+1

@Thavivelball:由於您沒有提供任何樣本輸入數據或預期輸出,因此我無法幫到您。 –

相關問題