简体   繁体   中英

How to compare elements of a list of lists (Python)

identical = 0
while x < len(BigList):
    while y < len(BigList):
        if BigList[x][0] == BigList[y][0] and y != x:
            identical += 1
        y += 1
    x += 1

How can I properly see if the 0th element of every list in big list is equal to another 0th element in another list in Big List?

ie, I need [[1,2],[2,3],[1,4],[2,5]] to make identical=2 because 2 lists have their 0th element equal to another list's 0th element

tia

identical = len(BigList) - len(set(item[0] for item in BigList))

重复数= BigList中的项目数减去唯一第零索引项目的数

first make a list of the 0th elements ... then count occurances (if you are 2.7+ you can use collections.Counter on your zeroth list

zeros = [mylist[0] for mylist in biglist]
my_dict = dict([(c,zeros.count(c)) for c in zeros])
dup_elems = filter(lambda key:my_dict[key]>1, my_dict.keys())
print len(dup_elems)
  1. Count the number of sublists that share the element at index 0.
  2. Count the number of identical sublists.
  3. The difference between the two is what you are after.

Code:

firstElems = zip(*L)[0]
firstSames = sum(v for v in collections.Counter(firstElems).values if v != 1)
equals = sum(v for v in collections.counter(tuple(l) for l in L).values if v!=1)
answer = firstSames - equals

Hope this helps.

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.

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