Utiliser sorted() pour la comparaison
Dans cette étape, vous apprendrez à utiliser la fonction sorted()
pour effectuer des comparaisons sans modifier la liste d'origine. La fonction sorted()
renvoie une nouvelle liste triée à partir d'un itérable, tandis que la méthode .sort()
trie la liste en place. Cela est utile lorsque vous souhaitez conserver la liste d'origine intacte.
Continuons à utiliser le fichier convert_to_set.py
dans votre répertoire ~/project
. Nous allons modifier le code pour utiliser sorted()
et le comparer avec la liste d'origine.
## Create a list with duplicate elements
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
## Convert the list to a set to remove duplicates
my_set = set(my_list)
## Convert the set back to a list
my_list_from_set = list(my_set)
## Use sorted() to get a new sorted list
sorted_list = sorted(my_list_from_set)
## Print the original list from set
print("Original list from set:", my_list_from_set)
## Print the sorted list
print("Sorted list:", sorted_list)
## Check if the original list is equal to the sorted list
if my_list_from_set == sorted_list:
print("The original list is sorted.")
else:
print("The original list is not sorted.")
Maintenant, exécutons le script Python. Ouvrez votre terminal et accédez au répertoire ~/project
:
cd ~/project
Ensuite, exécutez le script en utilisant la commande python
:
python convert_to_set.py
Vous devriez voir une sortie similaire à ceci :
Original list from set: [1, 2, 3, 4, 5, 6, 9]
Sorted list: [1, 2, 3, 4, 5, 6, 9]
The original list is sorted.
Dans ce cas, la liste d'origine obtenue à partir de l'ensemble était déjà triée. Modifions la liste d'origine pour nous assurer qu'elle n'est pas triée initialement.
## Create a list with duplicate elements
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
## Convert the list to a set to remove duplicates
my_set = set(my_list)
## Convert the set back to a list
my_list_from_set = list(my_set)
## Shuffle the list to make sure it's not sorted
import random
random.shuffle(my_list_from_set)
## Use sorted() to get a new sorted list
sorted_list = sorted(my_list_from_set)
## Print the original list from set
print("Original list from set:", my_list_from_set)
## Print the sorted list
print("Sorted list:", sorted_list)
## Check if the original list is equal to the sorted list
if my_list_from_set == sorted_list:
print("The original list is sorted.")
else:
print("The original list is not sorted.")
Exécutez le script à nouveau :
python convert_to_set.py
Vous devriez voir une sortie similaire à ceci :
Original list from set: [9, 2, 4, 5, 6, 1, 3]
Sorted list: [1, 2, 3, 4, 5, 6, 9]
The original list is not sorted.
Maintenant, la liste d'origine est mélangée, et la fonction sorted()
fournit une version triée pour la comparaison, démontrant que la liste d'origine reste inchangée.