[英]Comparing consequent strings in Python
Right now I have a string array and I want to loop through the string array and compare the value at one index with the value at the next index. 现在我有一个字符串数组,我想遍历该字符串数组,并将一个索引处的值与下一个索引处的值进行比较。 For example, if I was doing this in Java, the code would be something like this:
例如,如果我使用Java编写代码,则代码将如下所示:
string[] some = ["IP", "IP", "ADDRESS", "2342.42.2", "IP", "ASDF"];
for (int i = 0 ; i < some.length() ; i++)
if (some[i] == "IP" && some[i+1] == "ADDRESS")
int ipaddress = some[i+2];
I know that Python is a bit different, but basically I am trying to find the first IP ADDRESS. 我知道Python有点不同,但是基本上我正在尝试找到第一个IP地址。 How can I compare the current element and the next one in a loop?
如何在循环中比较当前元素和下一个元素?
This is a direct translation of your code. 这是您的代码的直接翻译。 In python
enumerate
iterates over a list as index,value pairs. 在python中,
enumerate
将列表作为索引,值对进行迭代。
>>> some = ["IP", "IP", "ADDRESS", "2342.42.2", "IP", "ASDF"];
>>> for i,v in enumerate(some):
... if v=="IP" and some[i+1] == "ADDRESS":
... ipaddress = some[i+2]
...
>>> ipaddress
'2342.42.2'
However you may consider end cases where there is no such stuff. 但是,您可以考虑没有这种东西的最终情况。 So you may as well so
for i,v in enumerate(some[:-2])
. 因此
for i,v in enumerate(some[:-2])
也是如此。 This will ensure that you will not get out of the bounds of the list otherwise you will get an IndexError
这将确保您不会超出列表的范围,否则会得到
IndexError
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.