仅使用for循环和split方法,我想计算名为mylist的字符串上有多少IP地址



仅使用for循环和split方法,我想计算名为my_list的字符串上有多少IP地址。

my_list = 
'''
inet addr :127.0.0.1 Mask:255.0.0.0
inet addr :127.0.0.2 Mask:255.0.0.0
inet addr :127.0.0.3 Mask:255.0.0.0
inet addr :127.0.0.4 Mask:255.0.0.0
'''
count = 0
for i in my_list : #this is the for loop but it returns 0 instead of 4
if i == "127" :
count = count + 1
print(count)

我觉得我错过了什么,但我想不通。感谢您的帮助

只是为了记录,str有一个count方法。

>>> my_list = 
...   '''
...   inet addr :127.0.0.1 Mask:255.0.0.0
...   inet addr :127.0.0.2 Mask:255.0.0.0
... 
...   inet addr :127.0.0.3 Mask:255.0.0.0
...   inet addr :127.0.0.4 Mask:255.0.0.0
...   '''
>>> my_list.count('inet')
4

您可以简单地将字符串每隔"inet";单词并计算元素。

由于拆分将在"inet"第一次出现之前创建一个空字符串,因此计数为1

my_string = """ inet addr :127.0.0.1 Mask:255.0.0.0 inet addr :127.0.0.2 Mask:255.0.0.0 inet addr :127.0.0.3 Mask:255.0.0.0 inet addr :127.0.0.4 Mask:255.0.0.0 
"""

count = len(my_string.strip().split("inet")) - 1
print(count)

运行时:

4

edit:如前一条评论中所述,它不是列表,而是字符串for循环对该字符串的每个字符进行迭代。由于字符不能是inet,因此条件始终是False,并且计数不递增。

qkzk发布的答案有效而且简单得多,但发布这个答案是因为你想使用for循环。

my_list = 
'''
inet addr :127.0.0.1 Mask:255.0.0.0
inet addr :127.0.0.2 Mask:255.0.0.0
inet addr :127.0.0.3 Mask:255.0.0.0
inet addr :127.0.0.4 Mask:255.0.0.0
'''
# split the string at each end of line to convert it to a list of string
my_list_of_strings = my_list.split('n')

count = 0
for string in my_list_of_strings: 
if "127" in string : # check if '127' is in string 
count = count + 1
print(count) 

输出

4

最新更新