Python multiple methods for de weighting lists of four methods

  • 2020-06-15 09:20:23
  • OfStack

Boring statistics on the following table to re-weight exactly how many ways. The following site gives you a summary of 1, the specific details are as follows;

In development, it is a very common requirement to de-weight arrays and lists. There are several methods to de-weight id in one list. The first two methods cannot guarantee the order, while the latter two methods can maintain the original order.

The following code has passed the test under Python3, please test by yourself under Python2

1. Use the special type of set. set of python is similar to other languages and is an unordered set of non-repeating elements


orgList = [1,0,3,7,7,5]
#list() The method is to put a string str Or tuples into arrays 
formatList = list(set(orgList))
print (formatList)

Results:

[0, 1, 3, 5, 7]

2. Use keys() method


orgList = [1,0,3,7,7,5]
#list() The method is to put a string str Or tuples into arrays 
formatList = list({}.fromkeys(orgList).keys())
print (formatList)

Results:

[0, 1, 3, 5, 7]

The problem with the above two approaches is that the result is not kept in the same order.

3. Cycle through the calendar


orgList = [1,0,3,7,7,5]
formatList = []
for id in orgList:
 if id not in formatList:
  formatList.append(id)
print (formatList)

Results:

[1, 0, 3, 7, 5]
but, this code is not concise enough, not high-end enough

4. Sort by index again


orgList = [1,0,3,7,7,5]
formatList = list(set(orgList))
formatList.sort(key=orgList.index)
print (formatList)

Results:

[1, 0, 3, 7, 5]

conclusion


Related articles: