get_unique_items_in_a_list
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
get_unique_items_in_a_list [2021/07/23 21:33] – created raju | get_unique_items_in_a_list [2021/07/23 22:14] (current) – [Notes and assumptions] raju | ||
---|---|---|---|
Line 1: | Line 1: | ||
===== Get unique items in a list ===== | ===== Get unique items in a list ===== | ||
==== Task ==== | ==== Task ==== | ||
- | Get the unique items from | + | Given |
< | < | ||
- | [' | + | mylist = [' |
</ | </ | ||
- | This can be one of three ways: | + | get the list of unique items. The output |
- Order does not matter. < | - Order does not matter. < | ||
[' | [' | ||
</ | </ | ||
- | - Preserve the order. Keep the first unique | + | - Preserve the order and keep the first unique |
[' | [' | ||
</ | </ | ||
- | - Preserve the order. Keep the last unique | + | - Preserve the order and keep the last unique |
[' | [' | ||
</ | </ | ||
+ | ==== Notes and assumptions ==== | ||
+ | * Starting from Python 3.7, dictionaries in python are ordered by insertion order. Per https:// | ||
+ | Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order | ||
+ | </ | ||
+ | * Assume Python >= 3.7 is used. | ||
+ | ==== Case 1: unique unordered ==== | ||
+ | < | ||
+ | uniq_no_order = list(set(mylist)) | ||
+ | print(uniq_no_order) | ||
+ | </ | ||
+ | |||
+ | < | ||
+ | [' | ||
+ | </ | ||
+ | |||
+ | ==== Case 2: keep first unique ==== | ||
+ | < | ||
+ | uniq_first = list({key:1 for key in mylist}.keys()) | ||
+ | print(uniq_first) | ||
+ | </ | ||
+ | |||
+ | < | ||
+ | [' | ||
+ | </ | ||
+ | |||
+ | ==== Case 3: keep last unique ==== | ||
+ | < | ||
+ | uniq_last = list({key:1 for key in mylist[:: | ||
+ | print(uniq_last) | ||
+ | </ | ||
+ | |||
+ | < | ||
+ | [' | ||
+ | </ |
get_unique_items_in_a_list.1627076023.txt.gz · Last modified: 2021/07/23 21:33 by raju