简体   繁体   English

pythonic从这个列表中提取字符串的方法

[英]pythonic way to extract string from this list

如果我有一个列表['default via 192.168.0.1 dev wlan0 proto static \\n', '192.168.0.0/24 dev wlan0 proto kernel scope link src 192.168.0.11 \\n']什么将是提取192.168.0.1最pythonic的方式192.168.0.1192.168.0.11

Try this using regular expressions, where lst is the list with the data: 使用正则表达式尝试此操作,其中lst是包含数据的列表:

import re
pat = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[^/]')
[pat.search(s).group(0) for s in lst]
=> ['192.168.0.1', '192.168.0.11']

The above assumes that there's a valid IPv4 IP in each string in the list, and that after the IP there isn't a / character. 以上假设列表中的每个字符串中都有一个有效的IPv4 IP,并且在IP之后没有/字符。

«Most pythonic» might be debatable, but something along these lines will work : «大多数pythonic»可能有争议,但这些方面的东西将起作用:

fct = lambda e : [w for w in e.split() if '.' in w and '/' not in w][0]
map( fct, l )

> ['192.168.0.1', '192.168.0.11']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM