简体   繁体   中英

Comparing elements of deque and list

I have currently this piece of code

import collections as c
a1 = ['a' , 'b','c']
q1 = c.deque(maxlen=3) 
q1.append('a')
q1.append('d')
q1.append('c')

q1 = list(q1)

counter = 0
for i in q1:
    if i == q1.dequeue():
        counter += 1

Is there any faster or more efficent way to compare the elements of 2 lists and evaluating the overlap between them? A set is not the way to go as i need the duplicate elements and they would have to be in order.

Lists are ordered elements. Hence my deqeue would have a length equivalent to the list.

I would to compute how much overlap is between the list and the dequeue.

Based on your revised question, I would take advantage of the fact that deque objects can be iterated by running over the zip of the list and deque objects. EG:

import collections as c
a1 = ['a' , 'b','c']
q1 = c.deque(maxlen=3) 
q1.append('a')
q1.append('d')
q1.append('c')
counter = sum(1 if a == q else 0 for (a, q) in zip(a1, q1))
# or, they're basically equivalent
counter = sum(1 for (a, q) in zip(a1, q1) if a == q)

That will compute the number of indices at which a1 and q1 have the same value, ending as soon as either is exhausted (so if a1 is 100 elements long, only the first three will be checked).

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