Sorting Visualization and Audibilization in OpenCV & Python

Latest Update

  • Add three more sorting algorithms: CombSort, RadixSort, MonkeySort
  • Now you can record the whole sorting procedure to *avi videos.
  • Adding -r in command line can get you Re-sampled data.
  • Adding -s in command line can get you Sparse data.

Introduction

This repository is a demo of visualizing 12 types of Sorting Algorithms. It aims to make Sorting Algorithms easier for programmers to understand. Also, you can see the difference of Time Complexity between different sorting algorithms.

Sorting AlgorithmAverageTime ComplexityBad Time ComplexityStability
Bubble SortO(N^2)O(N^2)YES
Insertion SortO(N^2)O(N^2)YES
Shell SortO(N^5/4)O(N^2)NO
Selection SortO(N^2)O(n^2)NO
Heap SortO(NlogN)O(NlogN)NO
Merge SortO(NlogN)O(NlogN)YES
Quick SortO(NlogN)O(N^2)NO
Bucket SortO(N)O(N)YES
Cycle SortO(N)O(N^2)NO
Comb SortO(N^2)O(N^2)NO
Radix SortO(N)O(N)YES
Monkey SortO(N!)O(N!)YES

Demos

Dependencies

  • python3.x
  • cv2
  • numpy
  • pygame

Quick Start

Check all dependencies installed

This command can help you install all the dependent packages

pip install -r requirements.txt

Clone this repository

git clone git@github.com:ZQPei/Sort_Visualization.git

Start

python main.py -l 512 -t BubbleSort

  • -l --length: Array Length
  • -t --sort-type: Sorting Type. Default type is BubbleSort
    • BubbleSort
    • InsertionSort
    • ShellSort
    • SelectionSort
    • HeapSort
    • MergeSort
    • QuickSort
    • BucketSort
    • CycleSort
    • CombSort
    • RadixSort(LSD)
    • MonkeySort
  • -i --interval: Time Interval of next frame
  • -r --resample: Get Resampled Array
  • -s --sparse: Sparse Array
  • -n --no-record: Don't record to *.avi video!
  • --silent: No voice output
  • --sound-interval: Time of sound

Download Details:
Author: ZQPei
Source Code: https://github.com/ZQPei/Sorting_Visualization
License: MIT License

#opencv  #python 

What is GEEK

Buddha Community

Sorting Visualization and Audibilization in OpenCV & Python
Duong Tran

Duong Tran

1646796864

Sắp Xếp Danh Sách Trong Python Với Python.sort ()

Trong bài viết này, bạn sẽ học cách sử dụng phương pháp danh sách của Python sort().

Bạn cũng sẽ tìm hiểu một cách khác để thực hiện sắp xếp trong Python bằng cách sử dụng sorted()hàm để bạn có thể thấy nó khác với nó như thế nào sort().

Cuối cùng, bạn sẽ biết những điều cơ bản về sắp xếp danh sách bằng Python và biết cách tùy chỉnh việc sắp xếp để phù hợp với nhu cầu của bạn.

Phương pháp sort() - Tổng quan về cú pháp

Phương pháp sort() này là một trong những cách bạn có thể sắp xếp danh sách trong Python.

Khi sử dụng sort(), bạn sắp xếp một danh sách tại chỗ . Điều này có nghĩa là danh sách ban đầu được sửa đổi trực tiếp. Cụ thể, thứ tự ban đầu của các phần tử bị thay đổi.

Cú pháp chung cho phương thức sort() này trông giống như sau:

list_name.sort(reverse=..., key=... )

Hãy chia nhỏ nó:

  • list_name là tên của danh sách bạn đang làm việc.
  • sort()là một trong những phương pháp danh sách của Python để sắp xếp và thay đổi danh sách. Nó sắp xếp các phần tử danh sách theo thứ tự tăng dần hoặc giảm dần .
  • sort()chấp nhận hai tham số tùy chọn .
  • reverse là tham số tùy chọn đầu tiên. Nó chỉ định liệu danh sách sẽ được sắp xếp theo thứ tự tăng dần hay giảm dần. Nó nhận một giá trị Boolean, nghĩa là giá trị đó là True hoặc False. Giá trị mặc định là False , nghĩa là danh sách được sắp xếp theo thứ tự tăng dần. Đặt nó thành True sẽ sắp xếp danh sách ngược lại, theo thứ tự giảm dần.
  • key là tham số tùy chọn thứ hai. Nó có một hàm hoặc phương pháp được sử dụng để chỉ định bất kỳ tiêu chí sắp xếp chi tiết nào mà bạn có thể có.

Phương sort()thức trả về None, có nghĩa là không có giá trị trả về vì nó chỉ sửa đổi danh sách ban đầu. Nó không trả về một danh sách mới.

Cách sắp xếp các mục trong danh sách theo thứ tự tăng dần bằng phương pháp sort()

Như đã đề cập trước đó, theo mặc định, sort()sắp xếp các mục trong danh sách theo thứ tự tăng dần.

Thứ tự tăng dần (hoặc tăng dần) có nghĩa là các mặt hàng được sắp xếp từ giá trị thấp nhất đến cao nhất.

Giá trị thấp nhất ở bên trái và giá trị cao nhất ở bên phải.

Cú pháp chung để thực hiện việc này sẽ giống như sau:

list_name.sort()

Hãy xem ví dụ sau đây cho thấy cách sắp xếp danh sách các số nguyên:

# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

#sort list in-place in ascending order
my_numbers.sort()

#print modified list
print(my_numbers)

#output

#[3, 7, 8, 10, 11, 22, 33, 54, 100]

Trong ví dụ trên, các số được sắp xếp từ nhỏ nhất đến lớn nhất.

Bạn cũng có thể đạt được điều tương tự khi làm việc với danh sách các chuỗi:

# a list of strings
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

#sort list in-place in alphabetical order
programming_languages.sort()

#print modified list
print(programming_languages)

#output

#['C++', 'Go', 'Java', 'Python', 'Rust', 'Swift']

Trong trường hợp này, mỗi chuỗi có trong danh sách được sắp xếp theo thứ tự không tuân theo.

Như bạn đã thấy trong cả hai ví dụ, danh sách ban đầu đã được thay đổi trực tiếp.

Cách sắp xếp các mục trong danh sách theo thứ tự giảm dần bằng phương pháp sort()

Thứ tự giảm dần (hoặc giảm dần) ngược lại với thứ tự tăng dần - các phần tử được sắp xếp từ giá trị cao nhất đến thấp nhất.

Để sắp xếp các mục trong danh sách theo thứ tự giảm dần, bạn cần sử dụng reverse tham số tùy chọn với phương thức sort() và đặt giá trị của nó thành True.

Cú pháp chung để thực hiện việc này sẽ giống như sau:

list_name.sort(reverse=True)

Hãy sử dụng lại cùng một ví dụ từ phần trước, nhưng lần này làm cho nó để các số được sắp xếp theo thứ tự ngược lại:

# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

#sort list in-place in descending order
my_numbers.sort(reverse=True)

#print modified list
print(my_numbers)

#output

#[100, 54, 33, 22, 11, 10, 8, 7, 3]

Bây giờ tất cả các số được sắp xếp ngược lại, với giá trị lớn nhất ở bên tay trái và giá trị nhỏ nhất ở bên phải.

Bạn cũng có thể đạt được điều tương tự khi làm việc với danh sách các chuỗi.

# a list of strings
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

#sort list in-place in  reverse alphabetical order
programming_languages.sort(reverse=True)

#print modified list
print(programming_languages)

#output

#['Swift', 'Rust', 'Python', 'Java', 'Go', 'C++']

Các mục danh sách hiện được sắp xếp theo thứ tự bảng chữ cái ngược lại.

Cách sắp xếp các mục trong danh sách bằng cách sử dụng key tham số với phương thức sort()

Bạn có thể sử dụng key tham số để thực hiện các thao tác sắp xếp tùy chỉnh hơn.

Giá trị được gán cho key tham số cần phải là thứ có thể gọi được.

Callable là thứ có thể được gọi, có nghĩa là nó có thể được gọi và tham chiếu.

Một số ví dụ về các đối tượng có thể gọi là các phương thức và hàm.

Phương thức hoặc hàm được gán cho key này sẽ được áp dụng cho tất cả các phần tử trong danh sách trước khi bất kỳ quá trình sắp xếp nào xảy ra và sẽ chỉ định logic cho tiêu chí sắp xếp.

Giả sử bạn muốn sắp xếp danh sách các chuỗi dựa trên độ dài của chúng.

Đối với điều đó, bạn chỉ định len()hàm tích hợp cho key tham số.

Hàm len()sẽ đếm độ dài của từng phần tử được lưu trong danh sách bằng cách đếm các ký tự có trong phần tử đó.

programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

programming_languages.sort(key=len)

print(programming_languages)

#output

#['Go', 'C++', 'Java', 'Rust', 'Swift', 'Python']

Trong ví dụ trên, các chuỗi được sắp xếp theo thứ tự tăng dần mặc định, nhưng lần này việc sắp xếp xảy ra dựa trên độ dài của chúng.

Chuỗi ngắn nhất ở bên trái và dài nhất ở bên phải.

Các keyreverse tham số cũng có thể được kết hợp.

Ví dụ: bạn có thể sắp xếp các mục trong danh sách dựa trên độ dài của chúng nhưng theo thứ tự giảm dần.

programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

programming_languages.sort(key=len, reverse=True)

print(programming_languages)

#output

#['Python', 'Swift', 'Java', 'Rust', 'C++', 'Go']

Trong ví dụ trên, các chuỗi đi từ dài nhất đến ngắn nhất.

Một điều cần lưu ý nữa là bạn có thể tạo một chức năng sắp xếp tùy chỉnh của riêng mình, để tạo các tiêu chí sắp xếp rõ ràng hơn.

Ví dụ: bạn có thể tạo một hàm cụ thể và sau đó sắp xếp danh sách theo giá trị trả về của hàm đó.

Giả sử bạn có một danh sách các từ điển với các ngôn ngữ lập trình và năm mà mỗi ngôn ngữ lập trình được tạo ra.

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

Bạn có thể xác định một hàm tùy chỉnh nhận giá trị của một khóa cụ thể từ từ điển.

💡 Hãy nhớ rằng khóa từ điển và key tham số sort()chấp nhận là hai thứ khác nhau!

Cụ thể, hàm sẽ lấy và trả về giá trị của year khóa trong danh sách từ điển, chỉ định năm mà mọi ngôn ngữ trong từ điển được tạo.

Giá trị trả về sau đó sẽ được áp dụng làm tiêu chí sắp xếp cho danh sách.

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

def get_year(element):
    return element['year']

Sau đó, bạn có thể sắp xếp theo giá trị trả về của hàm bạn đã tạo trước đó bằng cách gán nó cho key tham số và sắp xếp theo thứ tự thời gian tăng dần mặc định:

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

def get_year(element):
    return element['year']

programming_languages.sort(key=get_year)

print(programming_languages)

Đầu ra:

[{'language': 'C++', 'year': 1985}, {'language': 'Python', 'year': 1991}, {'language': 'Java', 'year': 1995}, {'language': 'Go', 'year': 2007}, {'language': 'Rust', 'year': 2010}, {'language': 'Swift', 'year': 2014}]

Nếu bạn muốn sắp xếp từ ngôn ngữ được tạo gần đây nhất đến ngôn ngữ cũ nhất hoặc theo thứ tự giảm dần, thì bạn sử dụng reverse=Truetham số:

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

def get_year(element):
    return element['year']

programming_languages.sort(key=get_year, reverse=True)

print(programming_languages)

Đầu ra:

[{'language': 'Swift', 'year': 2014}, {'language': 'Rust', 'year': 2010}, {'language': 'Go', 'year': 2007}, {'language': 'Java', 'year': 1995}, {'language': 'Python', 'year': 1991}, {'language': 'C++', 'year': 1985}]

Để đạt được kết quả chính xác, bạn có thể tạo một hàm lambda.

Thay vì sử dụng hàm tùy chỉnh thông thường mà bạn đã xác định bằng def từ khóa, bạn có thể:

  • tạo một biểu thức ngắn gọn một dòng,
  • và không xác định tên hàm như bạn đã làm với def hàm. Các hàm lambda còn được gọi là các hàm ẩn danh .
programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

programming_languages.sort(key=lambda element: element['year'])

print(programming_languages)

Hàm lambda được chỉ định với dòng key=lambda element: element['year']sắp xếp các ngôn ngữ lập trình này từ cũ nhất đến mới nhất.

Sự khác biệt giữa sort()sorted()

Phương sort()thức hoạt động theo cách tương tự như sorted()hàm.

Cú pháp chung của sorted()hàm trông như sau:

sorted(list_name,reverse=...,key=...)

Hãy chia nhỏ nó:

  • sorted()là một hàm tích hợp chấp nhận một có thể lặp lại. Sau đó, nó sắp xếp nó theo thứ tự tăng dần hoặc giảm dần.
  • sorted()chấp nhận ba tham số. Một tham số là bắt buộc và hai tham số còn lại là tùy chọn.
  • list_name là tham số bắt buộc . Trong trường hợp này, tham số là danh sách, nhưng sorted()chấp nhận bất kỳ đối tượng có thể lặp lại nào khác.
  • sorted()cũng chấp nhận các tham số tùy chọn reversekey, đó là các tham số tùy chọn tương tự mà phương thức sort() chấp nhận.

Sự khác biệt chính giữa sort()sorted()sorted()hàm nhận một danh sách và trả về một bản sao được sắp xếp mới của nó.

Bản sao mới chứa các phần tử của danh sách ban đầu theo thứ tự được sắp xếp.

Các phần tử trong danh sách ban đầu không bị ảnh hưởng và không thay đổi.

Vì vậy, để tóm tắt sự khác biệt:

  • Phương sort()thức không có giá trị trả về và trực tiếp sửa đổi danh sách ban đầu, thay đổi thứ tự của các phần tử chứa trong nó.
  • Mặt khác, sorted()hàm có giá trị trả về, là một bản sao đã được sắp xếp của danh sách ban đầu. Bản sao đó chứa các mục danh sách của danh sách ban đầu theo thứ tự được sắp xếp. Cuối cùng, danh sách ban đầu vẫn còn nguyên vẹn.

Hãy xem ví dụ sau để xem nó hoạt động như thế nào:

#original list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

#sort original list in default ascending order
my_numbers_sorted = sorted(my_numbers)

#print original list
print(my_numbers)

#print the copy of the original list that was created
print(my_numbers_sorted)

#output

#[10, 8, 3, 22, 33, 7, 11, 100, 54]
#[3, 7, 8, 10, 11, 22, 33, 54, 100]

Vì không có đối số bổ sung nào được cung cấp sorted(), nó đã sắp xếp bản sao của danh sách ban đầu theo thứ tự tăng dần mặc định, từ giá trị nhỏ nhất đến giá trị lớn nhất.

Và khi in danh sách ban đầu, bạn thấy rằng nó vẫn được giữ nguyên và các mục có thứ tự ban đầu.

Như bạn đã thấy trong ví dụ trên, bản sao của danh sách đã được gán cho một biến mới my_numbers_sorted,.

Một cái gì đó như vậy không thể được thực hiện với sort().

Hãy xem ví dụ sau để xem điều gì sẽ xảy ra nếu điều đó được thực hiện với phương thức sort().

my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

my_numbers_sorted = my_numbers.sort()

print(my_numbers)
print(my_numbers_sorted)

#output

#[3, 7, 8, 10, 11, 22, 33, 54, 100]
#None

Bạn thấy rằng giá trị trả về của sort()None.

Cuối cùng, một điều khác cần lưu ý là các reversekey tham số mà sorted()hàm chấp nhận hoạt động giống hệt như cách chúng thực hiện với phương thức sort() bạn đã thấy trong các phần trước.

Khi nào sử dụng sort()sorted()

Dưới đây là một số điều bạn có thể muốn xem xét khi quyết định có nên sử dụng sort()vs. sorted()

Trước tiên, hãy xem xét loại dữ liệu bạn đang làm việc:

  • Nếu bạn đang làm việc nghiêm ngặt với một danh sách ngay từ đầu, thì bạn sẽ cần phải sử dụng sort()phương pháp này vì sort()chỉ được gọi trong danh sách.
  • Mặt khác, nếu bạn muốn linh hoạt hơn và chưa làm việc với danh sách, thì bạn có thể sử dụng sorted(). Hàm sorted()chấp nhận và sắp xếp mọi thứ có thể lặp lại (như từ điển, bộ giá trị và bộ) chứ không chỉ danh sách.

Tiếp theo, một điều khác cần xem xét là liệu bạn có giữ được thứ tự ban đầu của danh sách mà bạn đang làm việc hay không:

  • Khi gọi sort(), danh sách ban đầu sẽ bị thay đổi và mất thứ tự ban đầu. Bạn sẽ không thể truy xuất vị trí ban đầu của các phần tử danh sách. Sử dụng sort()khi bạn chắc chắn muốn thay đổi danh sách đang làm việc và chắc chắn rằng bạn không muốn giữ lại thứ tự đã có.
  • Mặt khác, sorted()nó hữu ích khi bạn muốn tạo một danh sách mới nhưng bạn vẫn muốn giữ lại danh sách bạn đang làm việc. Hàm sorted()sẽ tạo một danh sách được sắp xếp mới với các phần tử danh sách được sắp xếp theo thứ tự mong muốn.

Cuối cùng, một điều khác mà bạn có thể muốn xem xét khi làm việc với các tập dữ liệu lớn hơn, đó là hiệu quả về thời gian và bộ nhớ:

  • Phương sort()pháp này chiếm dụng và tiêu tốn ít bộ nhớ hơn vì nó chỉ sắp xếp danh sách tại chỗ và không tạo ra danh sách mới không cần thiết mà bạn không cần. Vì lý do tương tự, nó cũng nhanh hơn một chút vì nó không tạo ra một bản sao. Điều này có thể hữu ích khi bạn đang làm việc với danh sách lớn hơn chứa nhiều phần tử hơn.

Phần kết luận

Và bạn có nó rồi đấy! Bây giờ bạn đã biết cách sắp xếp một danh sách trong Python bằng sort()phương pháp này.

Bạn cũng đã xem xét sự khác biệt chính giữa sắp xếp danh sách bằng cách sử dụng sort()sorted().

Tôi hy vọng bạn thấy bài viết này hữu ích.

Để tìm hiểu thêm về ngôn ngữ lập trình Python, hãy xem Chứng chỉ Máy tính Khoa học với Python của freeCodeCamp .

Bạn sẽ bắt đầu từ những điều cơ bản và học theo cách tương tác và thân thiện với người mới bắt đầu. Bạn cũng sẽ xây dựng năm dự án vào cuối để áp dụng vào thực tế và giúp củng cố những gì bạn đã học được.

Nguồn: https://www.freecodecamp.org/news/python-sort-how-to-sort-a-list-in-python/

#python 

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

August  Larson

August Larson

1662480600

The Most Commonly Used Data Structures in Python

In any programming language, we need to deal with data.  Now, one of the most fundamental things that we need to work with the data is to store, manage, and access it efficiently in an organized way so it can be utilized whenever required for our purposes. Data Structures are used to take care of all our needs.

What are Data Structures?

Data Structures are fundamental building blocks of a programming language. It aims to provide a systematic approach to fulfill all the requirements mentioned previously in the article. The data structures in Python are List, Tuple, Dictionary, and Set. They are regarded as implicit or built-in Data Structures in Python. We can use these data structures and apply numerous methods to them to manage, relate, manipulate and utilize our data.

We also have custom Data Structures that are user-defined namely Stack, Queue, Tree, Linked List, and Graph. They allow users to have full control over their functionality and use them for advanced programming purposes. However, we will be focussing on the built-in Data Structures for this article.

Implicit Data Structures Python

Implicit Data Structures Python

LIST

Lists help us to store our data sequentially with multiple data types. They are comparable to arrays with the exception that they can store different data types like strings and numbers at the same time. Every item or element in a list has an assigned index. Since Python uses 0-based indexing, the first element has an index of 0 and the counting goes on. The last element of a list starts with -1 which can be used to access the elements from the last to the first. To create a list we have to write the items inside the square brackets.

One of the most important things to remember about lists is that they are Mutable. This simply means that we can change an element in a list by accessing it directly as part of the assignment statement using the indexing operator.  We can also perform operations on our list to get desired output. Let’s go through the code to gain a better understanding of list and list operations.

1. Creating a List

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Output

['p', 'r', 'o', 'b', 'e']

2. Accessing items from the List

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Output

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Adding new items to the list

#adding item to the list
my_list + ['k']

Output

['p', 'r', 'o', 'b', 'e', 'k']

4. Removing Items

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Output

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Output

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Sorting List

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Output

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Output

['y', 'r', 'm', 'l', 'k']

6. Finding the length of a List

#finding the length of list
 
len(my_list)

Output

5

TUPLE

Tuples are very similar to lists with a key difference that a tuple is IMMUTABLE, unlike a list. Once we create a tuple or have a tuple, we are not allowed to change the elements inside it. However, if we have an element inside a tuple, which is a list itself, only then we can access or change within that list. To create a tuple, we have to write the items inside the parenthesis. Like the lists, we have similar methods which can be used with tuples. Let’s go through some code snippets to understand using tuples.

1. Creating a Tuple

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Output

('apple', 'banana', 'guava')

2. Accessing items from a Tuple

#accessing first element in tuple
 
my_tuple[1]

Output

'banana'

3. Length of a Tuple

#for finding the lenght of tuple
 
len(my_tuple)

Output

3

4. Converting a Tuple to List

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Output

list

5. Reversing a Tuple

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Output

('guava', 'banana', 'apple')

6. Sorting a Tuple

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Output

('apple', 'banana', 'guava')

7. Removing elements from Tuple

For removing elements from the tuple, we first converted the tuple into a list as we did in one of our methods above( Point No. 4) then followed the same process of the list, and explicitly removed an entire tuple, just using the del statement.

DICTIONARY

Dictionary is a collection which simply means that it is used to store a value with some key and extract the value given the key. We can think of it as a set of key: value pairs and every key in a dictionary is supposed to be unique so that we can access the corresponding values accordingly.

A dictionary is denoted by the use of curly braces { } containing the key: value pairs. Each of the pairs in a dictionary is comma separated. The elements in a dictionary are un-ordered the sequence does not matter while we are accessing or storing them.

They are MUTABLE which means that we can add, delete or update elements in a dictionary. Here are some code examples to get a better understanding of a dictionary in python.

An important point to note is that we can’t use a mutable object as a key in the dictionary. So, a list is not allowed as a key in the dictionary.

1. Creating a Dictionary

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Here, integers are the keys of the dictionary and the city name associated with integers are the values of the dictionary.

2. Accessing items from a Dictionary

#access an item
 
print(my_dict[1])

Output

'Delhi'

3. Length of a Dictionary

#length of the dictionary
 
len(my_dict)

Output

3

4. Sorting a Dictionary

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Output

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Adding elements in Dictionary

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Removing elements from Dictionary

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

SET

Set is another data type in python which is an unordered collection with no duplicate elements. Common use cases for a set are to remove duplicate values and to perform membership testing. Curly braces or the set() function can be used to create sets. One thing to keep in mind is that while creating an empty set, we have to use set(), and not { }. The latter creates an empty dictionary.

Here are some code examples to get a better understanding of sets in python.

1. Creating a Set

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Output

{'apple', 'strawberry', 'mango'}

2. Accessing items from a Set

#to test for an element inside the set
 
"apple" in my_set

Output

True

3. Length of a Set

print(len(my_set))

Output

3

4. Sorting a Set

print(sorted(my_set))

Output

['apple', 'mango', 'strawberry']

5. Adding elements in Set

my_set.add("guava")
print(my_set)

Output

{'apple', 'guava', 'mango', 'strawberry'}

6. Removing elements from Set

my_set.remove("mango")
print(my_set)

Output

{'apple', 'guava', 'strawberry'}

Conclusion

In this article, we went through the most commonly used data structures in python and also saw various methods associated with them.

Link: https://www.askpython.com/python/data

#python #datastructures

Наиболее часто используемые структуры данных в Python

В любом языке программирования нам нужно иметь дело с данными. Теперь одной из самых фундаментальных вещей, которые нам нужны для работы с данными, является эффективное хранение, управление и доступ к ним организованным образом, чтобы их можно было использовать всякий раз, когда это необходимо для наших целей. Структуры данных используются для удовлетворения всех наших потребностей.

Что такое структуры данных?

Структуры данных являются фундаментальными строительными блоками языка программирования. Он направлен на обеспечение системного подхода для выполнения всех требований, упомянутых ранее в статье. Структуры данных в Python — это List, Tuple, Dictionary и Set . Они считаются неявными или встроенными структурами данных в Python . Мы можем использовать эти структуры данных и применять к ним многочисленные методы для управления, связывания, манипулирования и использования наших данных.

У нас также есть пользовательские структуры данных, определяемые пользователем, а именно Stack , Queue , Tree , Linked List и Graph . Они позволяют пользователям полностью контролировать их функциональность и использовать их для расширенных целей программирования. Однако в этой статье мы сосредоточимся на встроенных структурах данных.

Неявные структуры данных Python

Неявные структуры данных Python

СПИСОК

Списки помогают нам хранить наши данные последовательно с несколькими типами данных. Они сопоставимы с массивами за исключением того, что они могут одновременно хранить разные типы данных, такие как строки и числа. Каждый элемент или элемент в списке имеет назначенный индекс. Поскольку Python использует индексацию на основе 0, первый элемент имеет индекс 0, и подсчет продолжается. Последний элемент списка начинается с -1, что можно использовать для доступа к элементам от последнего к первому. Чтобы создать список, мы должны написать элементы внутри квадратных скобок .

Одна из самых важных вещей, которые нужно помнить о списках , это то, что они изменяемы . Это просто означает, что мы можем изменить элемент в списке, обратившись к нему напрямую как часть оператора присваивания с помощью оператора индексации. Мы также можем выполнять операции в нашем списке, чтобы получить желаемый результат. Давайте рассмотрим код, чтобы лучше понять список и операции со списками.

1. Создание списка

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Выход

['p', 'r', 'o', 'b', 'e']

2. Доступ к элементам из списка

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Выход

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Добавление новых элементов в список

#adding item to the list
my_list + ['k']

Выход

['p', 'r', 'o', 'b', 'e', 'k']

4. Удаление элементов

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Выход

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Выход

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Список сортировки

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Выход

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Выход

['y', 'r', 'm', 'l', 'k']

6. Нахождение длины списка

#finding the length of list
 
len(my_list)

Выход

5

КОРТЕЖ

Кортежи очень похожи на списки с той ключевой разницей, что кортеж является IMMUTABLE , в отличие от списка. Как только мы создаем кортеж или имеем кортеж, нам не разрешается изменять элементы внутри него. Однако если у нас есть элемент внутри кортежа, который сам является списком, только тогда мы можем получить доступ к этому списку или изменить его. Чтобы создать кортеж, мы должны написать элементы внутри круглых скобок . Как и со списками, у нас есть аналогичные методы, которые можно использовать с кортежами. Давайте рассмотрим некоторые фрагменты кода, чтобы понять, как использовать кортежи.

1. Создание кортежа

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Выход

('apple', 'banana', 'guava')

2. Доступ к элементам из кортежа

#accessing first element in tuple
 
my_tuple[1]

Выход

'banana'

3. Длина кортежа

#for finding the lenght of tuple
 
len(my_tuple)

Выход

3

4. Преобразование кортежа в список

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Выход

list

5. Реверс кортежа

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Выход

('guava', 'banana', 'apple')

6. Сортировка кортежа

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Выход

('apple', 'banana', 'guava')

7. Удаление элементов из кортежа

Для удаления элементов из кортежа мы сначала преобразовали кортеж в список, как мы сделали в одном из наших методов выше (пункт № 4), затем следовали тому же процессу списка и явно удалили весь кортеж, просто используя del заявление .

ТОЛКОВЫЙ СЛОВАРЬ

Словарь — это коллекция, которая просто означает, что она используется для хранения значения с некоторым ключом и извлечения значения по данному ключу. Мы можем думать об этом как о наборе пар ключ: значение, и каждый ключ в словаре должен быть уникальным , чтобы мы могли получить соответствующий доступ к соответствующим значениям .

Словарь обозначается фигурными скобками { } , содержащими пары ключ: значение. Каждая из пар в словаре разделена запятой. Элементы в словаре неупорядочены , последовательность не имеет значения, пока мы обращаемся к ним или сохраняем их.

Они ИЗМЕНЯЕМЫ , что означает, что мы можем добавлять, удалять или обновлять элементы в словаре. Вот несколько примеров кода, чтобы лучше понять словарь в Python.

Важно отметить, что мы не можем использовать изменяемый объект в качестве ключа в словаре. Таким образом, список не допускается в качестве ключа в словаре.

1. Создание словаря

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Здесь целые числа — это ключи словаря, а название города, связанное с целыми числами, — это значения словаря.

2. Доступ к элементам из словаря

#access an item
 
print(my_dict[1])

Выход

'Delhi'

3. Длина словаря

#length of the dictionary
 
len(my_dict)

Выход

3

4. Сортировка словаря

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Выход

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Добавление элементов в Словарь

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Удаление элементов из словаря

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

УСТАНОВЛЕН

Set — это еще один тип данных в python, представляющий собой неупорядоченную коллекцию без повторяющихся элементов. Общие варианты использования набора — удаление повторяющихся значений и проверка принадлежности. Фигурные скобки или set()функция могут использоваться для создания наборов. Следует иметь в виду, что при создании пустого набора мы должны использовать set(), и . Последний создает пустой словарь. not { }

Вот несколько примеров кода, чтобы лучше понять наборы в python.

1. Создание набора

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Выход

{'apple', 'strawberry', 'mango'}

2. Доступ к элементам из набора

#to test for an element inside the set
 
"apple" in my_set

Выход

True

3. Длина набора

print(len(my_set))

Выход

3

4. Сортировка набора

print(sorted(my_set))

Выход

['apple', 'mango', 'strawberry']

5. Добавление элементов в Set

my_set.add("guava")
print(my_set)

Выход

{'apple', 'guava', 'mango', 'strawberry'}

6. Удаление элементов из Set

my_set.remove("mango")
print(my_set)

Выход

{'apple', 'guava', 'strawberry'}

Вывод

В этой статье мы рассмотрели наиболее часто используемые структуры данных в Python, а также рассмотрели различные связанные с ними методы.

Ссылка: https://www.askpython.com/python/data

#python #datastructures

Thierry  Perret

Thierry Perret

1662365538

Les Structures De Données Les Plus Couramment Utilisées En Python

Dans tout langage de programmation, nous devons traiter des données. Maintenant, l'une des choses les plus fondamentales dont nous avons besoin pour travailler avec les données est de les stocker, de les gérer et d'y accéder efficacement de manière organisée afin qu'elles puissent être utilisées chaque fois que cela est nécessaire pour nos besoins. Les structures de données sont utilisées pour répondre à tous nos besoins.

Que sont les Structures de Données ?

Les structures de données sont les blocs de construction fondamentaux d'un langage de programmation. Il vise à fournir une approche systématique pour répondre à toutes les exigences mentionnées précédemment dans l'article. Les structures de données en Python sont List, Tuple, Dictionary et Set . Ils sont considérés comme des structures de données implicites ou intégrées dans Python . Nous pouvons utiliser ces structures de données et leur appliquer de nombreuses méthodes pour gérer, relier, manipuler et utiliser nos données.

Nous avons également des structures de données personnalisées définies par l'utilisateur, à savoir Stack , Queue , Tree , Linked List et Graph . Ils permettent aux utilisateurs d'avoir un contrôle total sur leurs fonctionnalités et de les utiliser à des fins de programmation avancées. Cependant, nous nous concentrerons sur les structures de données intégrées pour cet article.

Structures de données implicites Python

Structures de données implicites Python

LISTE

Les listes nous aident à stocker nos données de manière séquentielle avec plusieurs types de données. Ils sont comparables aux tableaux à l'exception qu'ils peuvent stocker différents types de données comme des chaînes et des nombres en même temps. Chaque élément ou élément d'une liste a un index attribué. Étant donné que Python utilise l' indexation basée sur 0 , le premier élément a un index de 0 et le comptage continue. Le dernier élément d'une liste commence par -1 qui peut être utilisé pour accéder aux éléments du dernier au premier. Pour créer une liste, nous devons écrire les éléments à l'intérieur des crochets .

L'une des choses les plus importantes à retenir à propos des listes est qu'elles sont Mutable . Cela signifie simplement que nous pouvons modifier un élément dans une liste en y accédant directement dans le cadre de l'instruction d'affectation à l'aide de l'opérateur d'indexation. Nous pouvons également effectuer des opérations sur notre liste pour obtenir la sortie souhaitée. Passons en revue le code pour mieux comprendre les opérations de liste et de liste.

1. Créer une liste

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Production

['p', 'r', 'o', 'b', 'e']

2. Accéder aux éléments de la liste

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Production

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Ajouter de nouveaux éléments à la liste

#adding item to the list
my_list + ['k']

Production

['p', 'r', 'o', 'b', 'e', 'k']

4. Suppression d'éléments

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Production

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Production

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Liste de tri

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Production

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Production

['y', 'r', 'm', 'l', 'k']

6. Trouver la longueur d'une liste

#finding the length of list
 
len(my_list)

Production

5

TUPLE

Les tuples sont très similaires aux listes avec une différence clé qu'un tuple est IMMUTABLE , contrairement à une liste. Une fois que nous avons créé un tuple ou que nous avons un tuple, nous ne sommes pas autorisés à modifier les éléments qu'il contient. Cependant, si nous avons un élément à l'intérieur d'un tuple, qui est une liste elle-même, alors seulement nous pouvons accéder ou changer dans cette liste. Pour créer un tuple, nous devons écrire les éléments entre parenthèses . Comme les listes, nous avons des méthodes similaires qui peuvent être utilisées avec des tuples. Passons en revue quelques extraits de code pour comprendre l'utilisation des tuples.

1. Créer un tuple

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Production

('apple', 'banana', 'guava')

2. Accéder aux éléments d'un Tuple

#accessing first element in tuple
 
my_tuple[1]

Production

'banana'

3. Longueur d'un tuple

#for finding the lenght of tuple
 
len(my_tuple)

Production

3

4. Conversion d'un tuple en liste

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Production

list

5. Inverser un tuple

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Production

('guava', 'banana', 'apple')

6. Trier un tuple

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Production

('apple', 'banana', 'guava')

7. Supprimer des éléments de Tuple

Pour supprimer des éléments du tuple, nous avons d'abord converti le tuple en une liste comme nous l'avons fait dans l'une de nos méthodes ci-dessus (point n ° 4), puis avons suivi le même processus de la liste et avons explicitement supprimé un tuple entier, juste en utilisant le del déclaration .

DICTIONNAIRE

Dictionary est une collection, ce qui signifie simplement qu'il est utilisé pour stocker une valeur avec une clé et extraire la valeur donnée à la clé. Nous pouvons le considérer comme un ensemble de clés : des paires de valeurs et chaque clé d'un dictionnaire est supposée être unique afin que nous puissions accéder aux valeurs correspondantes en conséquence.

Un dictionnaire est indiqué par l'utilisation d' accolades { } contenant les paires clé : valeur. Chacune des paires d'un dictionnaire est séparée par des virgules. Les éléments d'un dictionnaire ne sont pas ordonnés , la séquence n'a pas d'importance pendant que nous y accédons ou que nous les stockons.

Ils sont MUTABLES ce qui signifie que nous pouvons ajouter, supprimer ou mettre à jour des éléments dans un dictionnaire. Voici quelques exemples de code pour mieux comprendre un dictionnaire en python.

Un point important à noter est que nous ne pouvons pas utiliser un objet mutable comme clé dans le dictionnaire. Ainsi, une liste n'est pas autorisée comme clé dans le dictionnaire.

1. Création d'un dictionnaire

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Ici, les entiers sont les clés du dictionnaire et le nom de ville associé aux entiers sont les valeurs du dictionnaire.

2. Accéder aux éléments d'un dictionnaire

#access an item
 
print(my_dict[1])

Production

'Delhi'

3. Longueur d'un dictionnaire

#length of the dictionary
 
len(my_dict)

Production

3

4. Trier un dictionnaire

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Production

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Ajout d'éléments dans le dictionnaire

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Suppression d'éléments du dictionnaire

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

POSITIONNER

Set est un autre type de données en python qui est une collection non ordonnée sans éléments en double. Les cas d'utilisation courants d'un ensemble consistent à supprimer les valeurs en double et à effectuer des tests d'appartenance. Les accolades ou la set()fonction peuvent être utilisées pour créer des ensembles. Une chose à garder à l'esprit est que lors de la création d'un ensemble vide, nous devons utiliser set(), et . Ce dernier crée un dictionnaire vide. not { }

Voici quelques exemples de code pour mieux comprendre les ensembles en python.

1. Créer un ensemble

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Production

{'apple', 'strawberry', 'mango'}

2. Accéder aux éléments d'un ensemble

#to test for an element inside the set
 
"apple" in my_set

Production

True

3. Longueur d'un ensemble

print(len(my_set))

Production

3

4. Trier un ensemble

print(sorted(my_set))

Production

['apple', 'mango', 'strawberry']

5. Ajout d'éléments dans Set

my_set.add("guava")
print(my_set)

Production

{'apple', 'guava', 'mango', 'strawberry'}

6. Suppression d'éléments de Set

my_set.remove("mango")
print(my_set)

Production

{'apple', 'guava', 'strawberry'}

Conclusion

Dans cet article, nous avons passé en revue les structures de données les plus couramment utilisées en python et avons également vu diverses méthodes qui leur sont associées.

Lien : https://www.askpython.com/python/data

#python #datastructures