Converting a list to a set changes element order
A
set
is an unordered data structure, so it does not preserve the insertion order.This depends on your requirements. If you have an normal list, and want to remove some set of elements while preserving the order of the list, you can do this with a list comprehension:
>>> a = [1, 2, 20, 6, 210]
>>> b = set([6, 20, 1])
>>> [x for x in a if x not in b]
[2, 210]If you need a data structure that supports both fast membership tests and preservation of insertion order, you can use the keys of a Python dictionary, which starting from Python 3.7 is guaranteed to preserve the insertion order:
>>> a = dict.fromkeys([1, 2, 20, 6, 210])
>>> b = dict.fromkeys([6, 20, 1])
>>> dict.fromkeys(x for x in a if x not in b)
{2: None, 210: None}b
doesn't really need to be ordered here – you could use aset
as well. Note thata.keys() - b.keys()
returns the set difference as aset
, so it won't preserve the insertion order.In older versions of Python, you can use
collections.OrderedDict
instead:>>> a = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210])
>>> b = collections.OrderedDict.fromkeys([6, 20, 1])
>>> collections.OrderedDict.fromkeys(x for x in a if x not in b)
OrderedDict([(2, None), (210, None)])
How to preserve the order of elements in list while converting it to set in Python and how to implement `scanf()` in Python?
In order to preserve the order you cannot use the set
object.But you can use frozenset
.Frozen set is just an immutable version of a Python set object.
So it goes like this,
>>> a = [1,2,3,4,5]
>>> b = frozenset(a)
>>> print(a)
[1, 2, 3, 4, 5]
>>> print(b)
frozenset({1, 2, 3, 4, 5})
For your second issue I suggest using this code.It doesn't break from the loop until an integer is given.
>>> while 1:
try:
x = int(input().strip())
break
except ValueError:
pass
string.strip() is used to remove all leading and trailing whitespaces in a python string.It still works without string.strip() though.
But it doesn't account for any '\n' of string values and loops until an integer is given.
In order to seperate the inputs by the ":" character in them you can simply use string.split(":")
.It returns a string with the values seperated.
>>> a = "1:2:3"
>>> b = a.split(":")
>>> print(b)
['1', '2', '3']
Hope this helps.
python reordering of list elements with conversion to set
Thats because sets are based on the Hash Table data structure, where records are stored in buckets using hash keys, and the order of items (when printed or converted to list) depends on the hashes, but internally the order doest matter. so it doesnt really bother to change the order, it just adds the item and creates a hash index for it. when you print the set it is probably printed according to the lexographical order of hashes, or something like that.
As you can see from the following, the list when created from a set, takes the same order of hashes of these items.
>>> s=set([5,4,3,7,6,2,1,0])
>>> s
{0, 1, 2, 3, 4, 5, 6, 7}
>>> list(s)
[0, 1, 2, 3, 4, 5, 6, 7]
Does python list(set(a)) change its order every time?
I would suggest an auxiliary set()
to ensure unicity when adding items on the list, thus preserving the order of your list()
, and not storing the set()
per se.
First, load your list and create a set with the contents
Before adding items to your list, check that they are not in the set (much faster search using "in" from the set rather than the list, specially if there are many elements)
Pickle your list, the order will be exactly the one you want
Drawback: takes twice as much memory than handling only a set()
Why is the element order changing once a sorted list converted to a set in Python?
According to the docs:
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
Here you should use:
from collections import OrderedDict
string = 'test'
result = sorted([character for character in string])
print(list(OrderedDict.fromkeys(result)))
Or if your version >= 3.7, dictionaries are ordered, so you can use:
string = 'test'
result = sorted([character for character in string])
print(list(dict.fromkeys(result)))
List to Set without affecting the order of the elements
Use LinkedHashSet
List<String> parameters = new ArrayList<String>();
Call the List here
|
Set<String> parameterSet=new LinkedHashSet<String>(parameters);
Related Topics
How to Define a Two-Dimensional Array
Meaning of @Classmethod and @Staticmethod For Beginner
How to Add New Keys to a Dictionary
Manually Raising (Throwing) an Exception in Python
How to Merge Dictionaries of Dictionaries
What Causes My Function to Return None At the End
How to Parallelize a Simple Python Loop
What Is the Syntax Rule For Having Trailing Commas in Tuple Definitions
Saving an Object (Data Persistence)
How to Print a Date in a Regular Format
Why Does Running the Flask Dev Server Run Itself Twice
How to Install a Python Package With a .Whl File
How to Get All Subsets of a Set - Powerset
How to Initialize a Dictionary of Distinct Empty Lists in Python