So, there is a list like
list=["one","two","ne","three"....]
I wonder, how do I compare each element of the list with others by using endswith() method? in this list, for example, list[0] endwith list[2].
I couldn't get how to make a comparison itself. I'm trying something like:
aa=list
flg=False
for i in range(len(ll)-1):
aa.append(ll[i+1])
if ll[i].endswith(aa[i]):
flg=True
however, it's good only for the first element, not with each one.
Using sets:
words = {"one","two","ne","three"}
[x for x in words if any(word.endswith(x) for word in words - {x})]
Out[69]: ['ne']
Basically, for each element, remove it from the words
set, and then test if any of the other words in the truncated set end with that word.
You are only doing a single pass through the list, even though you have stated your goal as " Compare each element of the list with the others ". This necessitates making one traversal of the list per element in the list . If you have n items, you will traverse the list n times for every item, for a total of n^2 traversals.
Hence, you need two for loops in your solution: one to traverse the list once and select the element that will be compared, and inside that loop, another that will check that element against the others.
for n in ll:
for m in ll:
if m.endswith(n) and m != n:
print(m, "ends with", n)
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.