python--Enhanced Edition list (deque) __python

Source: Internet
Author: User
Tags iterable

The collections module in Python provides a number of useful collection classes, where the deque can be described as a list of enhanced editions.

Deque basically have all the list methods:

From collections Import deque
q=deque ([1,2,3])
q.append (1)
print (q)
q.extend ([4,5])
print (q)
q.pop ()
print (q)
Run Result:

Deque ([1, 2, 3, 1])
deque ([1, 2, 3, 1, 4, 5])
deque ([1, 2, 3, 1, 4])

Deque (of course) is as iterable as a list:

M=map (str,q)
print (list (m))


The map function receives two parameters, the first is a function, and the second is the Iterable object. It passes the Iterable member to the function in turn, returning a map object. (Learn more: Http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014317852443934a86aa5bb5ea47fbbd5f35282b331335000)

The results are as follows, it is easy to convert a digital queue into a corresponding string list

[' 1 ', ' 2 ', ' 3 ', ' 1 ', ' 4 ']

In addition to the functions that these lists can satisfy, Deque has two "black magic" which is not available in the list.

Skill One: Limit the number of members

When a queue is created, the number of members is restricted by MaxLen, and the old member is automatically deleted when the new member joins and the queue is full.

From collections Import deque
q=deque ([1,2,3],maxlen=3)
q.append (4)
print (q)

The preceding code runs the result:
Deque ([2, 3, 4], maxlen=3)
Skill Two: Operation queue Head

When using the list, the Append and Pop methods are only for the end of the list, and if you want to add or remove members at the beginning of the queue, you need deque Appendleft and Popleft methods:

From collections Import deque
q=deque ([1,2,3])
q.appendleft (4)
Q.appendleft (5)
print (q)
Q.popleft ()
print (q)

The results of the above code run are obvious:

Deque ([5, 4, 1, 2, 3])
deque ([4, 1, 2, 3])




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.