List of Python go heavy

Source: Internet
Author: User

The problem is to go to the news ID in a list and go back to the weight to ensure that the order is not changed.

Intuitive approach

The simplest idea is to:

Copy CodeThe code is as follows:
ids = [1,2,3,3,4,2,3,4,5,6,1]
News_ids = []
For ID in IDs:
If ID not in News_ids:
News_ids.append (ID)

Print News_ids

It works, but it doesn't look cool enough.

With Set

Another solution is to use set:

Copy CodeThe code is as follows:
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = List (set (IDS))


This result is not maintained in the original order.

Sort by index again

Finally, this approach solves:

Copy CodeThe code is as follows:
ids = [1,4,3,3,4,2,3,4,5,6,1]
News_ids = List (set (IDS))
News_ids.sort (Ids.index)

Using Itertools.grouby

The article mentions Itertools.grouby from the beginning, which can be used if the list order is not considered:

Copy CodeThe code is as follows:
ids = [1,4,3,3,4,2,3,4,5,6,1]
Ids.sort ()
it = itertools.groupby (IDs)

For K, G in it:
Print K

The principle of itertools.groupby can be seen here: http://docs.python.org/2/library/itertools.html#itertools.groupby

Users add: With reduce

The Netizen reatlk the message to the other solution. I add and explain here:

Copy CodeThe code is as follows:
In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1]

In [6]: func = lambda x,y:x if y in x else x + [y]

In [7]: Reduce (func, [[],] + IDs)
OUT[7]: [1, 4, 3, 2, 5, 6]


Above is the code I run in Ipython, where Lambda x,y:x if y in x else x + [y] is equivalent to lambda x,y:y in X and X or X+[y].

The idea is to turn IDs into [[], 1,4,3,......] and then take advantage of the features of reduce. Reduce explanation see here: http://docs.python.org/2/library/functions.html#reduce

List of Python go heavy

Related Article

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.