str1 = ['106.51.107.185', '122.169.20.139', '123.201.53.226']
str2 = ['106.51.107.185', '122.169.20.138', '123.201.53.226']
I need to match the above string based on their respective Index.
str1[0] match str2[0]
str1[1] match str2[1]
str1[2] match str2[2]
based on the match i need the output.
I tried from my end, between the 2 strings, str[0] is checking the match with str2[:], it need to match only with the respective indexes alone. Please assist.
Thanks !!!
You can use:
from operator import eq
map(eq, str1, str2)
This will produce an iterable of booleans ( True
or False
) in python-3.x , and a list of booleans in python-2.x . In case you want a list in python-3.x , you can use the list(..)
construct over the map(..)
:
from operator import eq
map(eq, str1, str2)
This works since map
takes as first argument a function (here eq
from the operator
package), and one or more iterables). It will then call that function on the arguments of the iterables (so the first item of str1
and str2
, then the second item of str1
and str2
, and so on). The outcome of that function call is yielded.
Alternatively, we can use list comprehension, to get the indices, for example:
same_indices = [i for i, (x, y) for enumerate(zip(str1, str2)) if x == y]
or the different ones:
diff_indices = [i for i, (x, y) for enumerate(zip(str1, str2)) if x != y]
We can also reuse the above map
result with:
from operator import eq, itemgetter
are_same = map(eq, str1, str2)
same_indices = map(itemgetter(0),
filter(itemgetter(1), enumerate(are_same))
)
If we then convert same_indices
to a list, we get:
>>> list(same_indices)
[0, 2]
We can also perform such construct on are_diff
:
from operator import , itemgetter
are_ = map(, str1, str2)
_indices = map(itemgetter(0),
filter(itemgetter(1), enumerate(are_))
)
You can use zip and list comprehension ie
[i==j for i,j in zip(str1,str2)]
[True, False, True]
Following is a simple solution using for
loop:
res = []
for i in range(len(str1)):
res.append(str1[i] == str2[i])
print(res)
Output:
[True, False, True]
One can also use list comprehension
for this:
res = [ (str1[i] == str2[i]) for i in range(len(str1)) ]
Edit: to get indexes of matched and non-matched:
matched = []
non_matched = []
for i in range(len(str1)):
if str1[i] == str2[i]:
matched.append(i)
else:
non_matched.append(i)
print("matched:",matched)
print("non-matched:", non_matched)
Output:
matched: [0, 2]
non-matched: [1]
我不确定所需的确切输出,但是,如果要比较这两个列表并得到它们之间的差,可以将它们转换为set,然后将它们减去,如下所示:
st = str(set(str1) - set(str2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.