如何将列表中的每个项目与其他项目进行比较,只比较一次?

假设我有一个数组/列表要比较。在我更熟悉的语言中,我会这样做

for (int i = 0, i < mylist.size(); i++)
for (int j = i + 1, j < mylist.size(); j++)
compare(mylist[i], mylist[j])

这确保了我们只比较每一对。对于某些上下文,我正在对列表中包含的一些对象进行碰撞侦测。对于检测到的每个碰撞,一个描述碰撞的小“碰撞”对象被附加到一个列表中,然后另一个例程循环通过解决每个碰撞(取决于两个碰撞对象的性质)。显然,我只想报告一次每次碰撞。

既然 Python 喜欢使用迭代器而不是遍历索引,那么 pythonic 的方法是什么呢?

我有以下(bug)代码:

for this in mylist:
for that in mylist:
compare(this, that)

但是很明显每次碰撞都会被检测到两次,这就导致了一些奇怪的行为,当我们试图解决它们的时候。那么 Python 的解决方案是什么呢?

294077 次浏览

Use itertools.combinations(mylist, 2)

mylist = range(5)
for x,y in itertools.combinations(mylist, 2):
print x,y


0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4

Of course this will generate each pair twice as each for loop will go through every item of the list.

You could use some itertools magic here to generate all possible combinations:

import itertools
for a, b in itertools.combinations(mylist, 2):
compare(a, b)

itertools.combinations will pair each element with each other element in the iterable, but only once.


You could still write this using index-based item access, equivalent to what you are used to, using nested for loops:

for i in range(len(mylist)):
for j in range(i + 1, len(mylist)):
compare(mylist[i], mylist[j])

Of course this may not look as nice and pythonic but sometimes this is still the easiest and most comprehensible solution, so you should not shy away from solving problems like that.

This code will count frequency and remove duplicate elements:

from collections import Counter


str1='the cat sat on the hat hat'


int_list=str1.split();


unique_list = []
for el in int_list:


if el not in unique_list:
unique_list.append(el)
else:
print "Element already in the list"


print unique_list


c=Counter(int_list)


c.values()


c.keys()


print c

I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:

for index, this in enumerate(mylist):
for that in mylist[index+1:]:
compare(this, that)

Find the other answer for this program in simple way..

def Compare_two_list(list_1, list_2):
data_len = len(list_1)
for i in range(data_len):
if list_1[i] <= list_2[i] :
print("Less than or equal")
else:
get_data.append(list_2[i])
print("greater than")`