Features of Python's several techniques

Source: Internet
Author: User

Today by chance to see an article < You may not know the 30 Python language of the lifting point skills, although the python for several years, but the middle is still a lot of do not know or do not think, special here to do the next excerpt.

Original address: http://soft.chinabyte.com/database/379/12920379.shtml

1. Named slices

>>> a = [012345]>>> lastthree = Slice (-3, none)>>> lastthreeslice (-3, none, none)> >> a[lastthree][345]

2. zip packaging and Unpacking list

>>> a = [1,2,3]>>> B = ['a','b','C']>>> z =Zip (A, b)>>>z[(1,'a'), (2,'b'), (3,'C')]>>>>>> Zip (*z) [(1,2,3), ('a','b','C')]

3. Use zip to merge adjacent list items

>>> a=[1,2,3,4,5]>>> Zip (* ([ITER (a)]* 2 )) [(12), (34), (56)]
>>>
>>> Zip (A[::2], a[1::2])
[(1, 2), (3, 4), (5, 6)]

Can be written as an anonymous function

Lambda A, k:zip (* ([ITER (a)]*k))

Or

Lambda  for  in range (k)))

Where a identifies the list to be merged, and K indicates that the adjacent K elements are to be merged

>>> Group_adjacent_1 (A,3) [(1,2,3), (4,5,6)] >>> Group_adjacent_1 (A,1) [(1,), (2,), (3,), (4,), (5,), (6,)]
>>>
>>>
>>> Group_adjacent_2 (A, 3)
[(1, 2, 3), (4, 5, 6)]
>>> Group_adjacent_2 (A, 1)
[(1, 2, 3), (4, 5, 6)]

4. Creating a sliding window using zip and iterators

 from Import Islice def N_grams (A, N): ...     Z -in range (     N) ...  return Zip (*>>> a = [1, 2, 3, 4, 5, 6]>>> n_grams (A, 3) [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

Features of Python's several techniques

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.