Python loop using the index number as part of a key name
I'm new to Python - getting my feet wet.
I want to create a loop that looks for ip addresses and uses the loop count as part of a key name.
i.e.
i 开发者_JS百科= 0
while i < 5:
ip1= re.search(r'(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}', commandslist)
if ip1:
myip1 = ip1.group()
commandslist = commandslist.replace(myip1,'')
print 'found', ip1.group()
i=i+1
what I'd like to do is where it says ip1 or myip1 replace the 1 with the current value of i. I've tried ip[i] and that just tosses errors about not being defined. defining ip=range(0,5) doesn't seem to help at all.
Can anyone point me back to the correct path? Thank you.
No loop is necessary, you can simply write:
myip = re.findall(r'(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}', commandslist)
When you really need loops, avoid this:
i = 0
while i < 5:
# do something with i
i = i + 1
and use this instead:
for i in xrange(5):
# do something with i
When you need to iterate over elements of a list, use this:
for e in l:
# do something with e
In your case, a complete example might look like:
import re
commandslist = 'Lorem 192.168.0.1, ipsum 127.0.0.1: 10.0.0.1 and 10.0.0.2.'
myips = re.findall(r'(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}', commandslist)
for ip in myips:
print 'found ', ip
ip = [None, ] * 5
myip = [None, ] * 5
Add this above your code. Then you use it like this: ip[i] = ...
, myip[i] = ...
Python encourages the programmer to allocate space for storage when it is needed.
In your attempt, allocate empty lists for ip
and myip
, then use .append
to add elements when necessary.
The lists will grow to any (reasonable) length, and the code will not depend on initial allocation size.
The ip[-1]
notation references the last element of a sequence.
The running index i
is not used inside the loop.
ip = []
myip = []
i = 0
while i < 5:
ip.append(re.search(r'(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}', commandslist))
if ip[-1]:
myip.append(ip[-1].group())
commandslist = commandslist.replace(myip[-1],'')
print 'found', ip[-1].group()
i=i+1
Please go over the tutorial, and pay special attention to the lists
introduction.
精彩评论