set(sorted()) method in python [duplicate] - python

This question already has answers here:
Sorting a set of values
(2 answers)
Closed 1 year ago.
When I used sorted on the set in python it returns sorted list. But I want to return the set. I tried set(sorted()) but it doesn't sort the set.
I tried another way. But why set(sorted()) isn't sorting the set?
my tried code

Sets are unsorted, that is their nature. Taking a set (or any collection) then sorting it, then making a set out of that, will be unlikely to produce sorted results.
If you require the items in a sorted manner, you should turn them into something that can be sorted (like a list, which is what you get from sorted(someSet)). For example:
>>> a = {100, 99, 1, 2, 5, 6} # A set
>>> sorted(a) # A sorted list from that set.
[1, 2, 5, 6, 99, 100]
>>> set(sorted(a)) # An (unsorted) set from that sorted list.
{1, 2, 99, 100, 5, 6}

Related

Dicts not being popped from list? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 months ago.
The context doesn't matter too much, but I came across the problem that while trying to pop dict objects from a list, it wouldn't delete all of them. I'm doing this to filter for certain values in the dict objects, and I was left with things that should have been removed. Just to see what would happen, I tried deleting every item in the list called accepted_auctions (shown below), but it did not work.
for auction in accepted_auctions:
accepted_auctions.pop(accepted_auctions.index(auction))
print(len(accepted_auctions))
When I tested this code, print(len(accepted_auctions)) printed 44 into the console.
What am I doing wrong?
Modifying a list as you iterate over it will invalidate the iterator (because the indices of all the items are changing as you remove items), which in turn causes it to skip items. Don't do that.
The easiest way to create a filtered list is via a list comprehension that creates a new list, e.g.:
accepted_auctions = [a for a in accepted_auctions if something(a)]
Here's a simple example using a list comprehension to filter a list of ints to only the odd numbers:
>>> nums = list(range(10))
>>> nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> nums = [n for n in nums if n % 2]
>>> nums
[1, 3, 5, 7, 9]

Removing a list from repeated members using list comprehension instead of the usual for loop [duplicate]

This question already has answers here:
Remove duplicates from list python
(4 answers)
Closed 4 years ago.
I have learned that I can use the so-called list comprehension to make python 'for loops' shorter if I want to create a list. For example, instead of writing:
b = []
a = [2, 3, 5]
for x in a:
b.append(x**2)
I can write my code like this:
b = [x**2 for x in a]
I was wondering how can I convert the below code to the second shorter format:
lst = [1, 2, 3, 3, 4, 5, 5]
u_lst = []
for x in lst:
if x not in u_lst:
u_lst.append(x)
As #PritoshSingh has pointed out in the comment, a list construction that involves references to items already constructed in the same list is not suitable for the use of a list comprehension, which is best for value mapping and/or filtering based on conditions not involving the list being constructed itself.
The problem you're describing can be best solved by using the dict.from_keys method, which ignores items it has already seen as it reads from the given sequence:
u_list = list(dict.from_keys(lst))
Use collections.OrderedDict in place of dict if you're using Python 3.6 or earlier versions, where order of dict keys is not guaranteed.
From the specific example given it seems like you want u_lst to be a list of unique values only. If so, there is no need for any list comprehensions, just use a set on the original list:
lst = [1, 2, 3, 3, 4, 5, 5]
u_lst = list(set(lst))
Outputs {1, 2, 3, 4, 5} without converting into a list and [1, 2, 3, 4, 5] with it.
Note that using set on a list produces a set, to get it to behave as a list, you would then convert it into a list as above.

Finding elements that appear in all sets in a list of sets [duplicate]

This question already has answers here:
Best way to find the intersection of multiple sets?
(7 answers)
Closed 5 years ago.
I have a list of n sets of integers denoted as lst = [S1, S2, S3 ... Sn] and I want to find the intersection of all the sets.
Is there an optimal way to do this?
If you have a list sets, you can trivially get their intersection with:
set.intersection(*lst)
This will produce a new set with only those values that are common between all the sets:
>>> lst = [{1, 2, 3}, {3, 5}, {2, 3}]
>>> set.intersection(*lst)
{3}
Edit: Misread, thought that you have multiple lists of numbers and generally asking how to find those numbers that are present in all of them. Will keep the original answer below, though, as some people still found it helpful to some degree.
Yes, it's called set intersection and can be used on the set data type.
Demo:
>>> s = set((1, 2, 3))
>>> s2 = set((2, 3, 4))
>>> s3 = set((3, 4, 5))
>>> s & s2
{2, 3}
>>> s & s2 & s3
{3}
If your current data is stored in lists, converting it to sets is just a matter of passing the lists to the set() constructor:
>>> numbers = [2, 7, 9, 10]
>>> set(numbers)
{2, 7, 9, 10}
Mind, though, that if a list contains duplicates, that information will get lost, and each duplicated element will only be present once in the resulting intersection.

append values in a list without sorting python, keeping the appending order [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 7 years ago.
I am producing a list of list by this code, it is just a condition for a column of a dataframe named lvl or "Level", then append the index of this condition values, so the problem that i got is that the order of appending is important to me,
for i in range(1,int(24-lvl)):
j=list2[(list2.lvl==(lvl+i))]
jj=[]
jj.append(j.index)
print itertools.chain(jj)
well for example, the answer should be:
[0,100,110,500,501,550,555,89,120,114]
but i get the same list but sorted
[0,89,100,110,114,120,500,501,550,555]
itertools.chain works for me. You need to unpack the list before passing it to chain method.
>>> l = [[1,5],[10,2],[6,9,3]]
>>> list(itertools.chain(*l))
[1, 5, 10, 2, 6, 9, 3]
You can simply do it with list comprehension:
>>> l = [[1,5],[10,2],[6,9,3]]
>>> l_out = [item for sub_l in l for item in sub_l]
>>> l_out
[1, 5, 10, 2, 6, 9, 3]

Moving values but preserving order in a Python list [duplicate]

This question already has answers here:
Python list rotation [duplicate]
(4 answers)
Closed 7 years ago.
I have a list
a=[1,2,3,4,5]
and want to 'move' its values so it changes into
a=[2,3,4,5,1]
and the next step
a=[3,4,5,1,2]
Is there a built-in function in Python to do that?
Or is there a shorter or nicer way than
b=[a[-1]]; b.extend(a[:-1]); a=b
>>> a = [1,2,3,4,5]
>>> a.append(a.pop(0))
>>> a
[2, 3, 4, 5, 1]
This is expensive, though, as it has to shift the contents of the entire list, which is O(n). A better choice may be to use collections.deque if it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:
>>> a = collections.deque([1,2,3,4,5])
>>> a
deque([1, 2, 3, 4, 5])
>>> a.rotate(-1)
>>> a
deque([2, 3, 4, 5, 1])
Note also that both these solutions involve changing the original sequence object, whereas yours creates a new list and assigns it to a. So if we did:
>>> c = a
>>> # rotate a
With your method, c would continue to refer to the original, unrotated list, and with my methods, it will refer to the updated, rotated list/deque.

Categories