简体   繁体   English

将每个列表的元素与列表中的其他元素进行比较

[英]Compare each list's element with others in the list

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? 我想知道,如何使用endswith()方法将列表中的每个元素与其他元素进行比较? in this list, for example, list[0] endwith list[2]. 在此列表中,例如,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. 基本上,对于每个元素,将其从words集中删除,然后测试截断集中的任何其他单词是否以该单词结尾。

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. 如果您有n个项目,则每个项目将遍历列表n次,总共n ^ 2次遍历。

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循环:一个遍历列表一次并选择将要比较的元素,并在该循环内,另一个将检查该元素与其他元素。

for n in ll:
    for m in ll:
        if m.endswith(n) and m != n:
            print(m, "ends with", n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM