CODE VN

CODE VN

1649328720

Cách triển khai Merge Sort trong Python

Thuật toán Merge Sort là một thuật toán chia và chinh phục lấy một mảng làm đầu vào và sau đó chia mảng hoàn chỉnh thành các mảng con gồm các phần tử đơn lẻ. Kết quả là, chúng ta còn lại rất nhiều mảng được sắp xếp vì phần tử đơn luôn được sắp xếp. Sau đó, chúng tôi hợp nhất tất cả các mảng bằng cách lấy hai mảng cùng một lúc cho đến khi chúng tôi nhận được một mảng được sắp xếp cuối cùng.

Trong bài viết này, Chúng tôi sẽ hướng dẫn bạn cách triển khai Merge Sort bằng Python.

Tôi hy vọng bây giờ bạn đã hiểu thuật toán sắp xếp hợp nhất trong khoa học máy tính là gì. Để triển khai thuật toán sắp xếp hợp nhất bằng Python, trước tiên chúng ta cần chia một mảng thành nhiều mảng gồm các phần tử đơn lẻ và sau đó chúng ta có thể dễ dàng hợp nhất chúng thành một mảng được sắp xếp cuối cùng. Bây giờ chúng ta hãy xem cách triển khai sắp xếp hợp nhất bằng Python:

def merge(listA, listB):
    newlist = list()
    a = 0
    b = 0
    while a < len(listA) and b < len(listB):
        if listA[a] < listB[b]:
            newlist.append(listA[a])
            a += 1
        else:
            newlist.append(listB[b])
            b += 1
    while a < len(listA):
        newlist.append(listA[a])
        a += 1
    while b < len(listB):
        newlist.append(listB[b])
        b += 1
    return newlist

def merge_sort(input_list):
    if len(input_list) <= 1:
        return input_list
    else:
        mid = len(input_list) // 2
        left = merge_sort(input_list[:mid])
        right = merge_sort(input_list[mid:])
        newlist = merge(left, right)
        return newlist

a = [56, 89, 45, 34, 90, 32, 20, 67, 43]
print(merge_sort(a))

Đầu ra:

[20, 32, 34, 43, 45, 56, 67, 89, 90]

Đây là cách bạn có thể triển khai thuật toán sắp xếp hợp nhất bằng Python. Đây hiện là cách tiếp cận hiệu quả nhất để sắp xếp mảng trong số tất cả các thuật toán sắp xếp trong khoa học máy tính

What is GEEK

Buddha Community

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

Dang  Tu

Dang Tu

1662380058

Các Cấu Trúc Dữ Liệu được Sử Dụng Phổ Biến Nhất Trong Python

Trong bất kỳ ngôn ngữ lập trình nào, chúng ta cần xử lý dữ liệu. Bây giờ, một trong những điều cơ bản nhất mà chúng ta cần làm việc với dữ liệu là lưu trữ, quản lý và truy cập nó một cách hiệu quả theo cách có tổ chức để nó có thể được sử dụng bất cứ khi nào được yêu cầu cho các mục đích của chúng ta. Cấu trúc dữ liệu được sử dụng để đáp ứng mọi nhu cầu của chúng tôi.

Cấu trúc dữ liệu là gì?

Cấu trúc dữ liệu là các khối xây dựng cơ bản của một ngôn ngữ lập trình. Nó nhằm mục đích cung cấp một cách tiếp cận có hệ thống để đáp ứng tất cả các yêu cầu được đề cập trước đó trong bài báo. Các cấu trúc dữ liệu trong Python là Danh sách, Tuple, Từ điển và Tập hợp . Chúng được coi là Cấu trúc dữ liệu ngầm định hoặc được tích hợp sẵn trong Python . Chúng tôi có thể sử dụng các cấu trúc dữ liệu này và áp dụng nhiều phương pháp cho chúng để quản lý, liên quan, thao tác và sử dụng dữ liệu của chúng tôi.

Chúng tôi cũng có các Cấu trúc Dữ liệu tùy chỉnh do người dùng xác định cụ thể là Ngăn xếp , Hàng đợi , Cây , Danh sách được Liên kếtĐồ thị . Chúng cho phép người dùng có toàn quyền kiểm soát chức năng của chúng và sử dụng chúng cho các mục đích lập trình nâng cao. Tuy nhiên, chúng tôi sẽ tập trung vào Cấu trúc dữ liệu tích hợp cho bài viết này.

Python cấu trúc dữ liệu ngầm

Python cấu trúc dữ liệu ngầm

DANH SÁCH

Danh sách giúp chúng tôi lưu trữ dữ liệu của mình một cách tuần tự với nhiều kiểu dữ liệu. Chúng có thể so sánh với mảng với ngoại lệ là chúng có thể lưu trữ các kiểu dữ liệu khác nhau như chuỗi và số cùng một lúc. Mỗi mục hoặc phần tử trong danh sách đều có một chỉ mục được chỉ định. Vì Python sử dụng lập chỉ mục dựa trên 0 , phần tử đầu tiên có chỉ mục là 0 và việc đếm vẫn tiếp tục. Phần tử cuối cùng của danh sách bắt đầu bằng -1 có thể được sử dụng để truy cập các phần tử từ cuối cùng đến đầu tiên. Để tạo một danh sách, chúng ta phải viết các mục bên trong dấu ngoặc vuông .

Một trong những điều quan trọng nhất cần nhớ về danh sách là chúng có thể thay đổi . Điều này đơn giản có nghĩa là chúng ta có thể thay đổi một phần tử trong danh sách bằng cách truy cập trực tiếp vào nó như một phần của câu lệnh gán bằng cách sử dụng toán tử lập chỉ mục. Chúng tôi cũng có thể thực hiện các thao tác trên danh sách của mình để có được đầu ra mong muốn. Chúng ta hãy đi qua đoạn mã để hiểu rõ hơn về danh sách và các hoạt động của danh sách.

1. Tạo danh sách

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

Đầu ra

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

2. Truy cập các mục từ Danh sách

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

Đầu ra

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

3. Thêm các mục mới vào danh sách

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

Đầu ra

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

4. Loại bỏ các mục

#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)

Đầu ra

['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)

Đầu ra

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

5. Danh sách sắp xếp

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

Đầu ra

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

Đầu ra

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

6. Tìm độ dài của một danh sách

#finding the length of list
 
len(my_list)

Đầu ra

5

TUPLE

Tuple rất giống với danh sách với một điểm khác biệt chính là tuple là NGAY LẬP TỨC , không giống như một danh sách. Khi chúng tôi tạo một bộ hoặc có một bộ, chúng tôi không được phép thay đổi các phần tử bên trong nó. Tuy nhiên, nếu chúng ta có một phần tử bên trong một tuple, chính là một danh sách, thì chỉ khi đó chúng ta mới có thể truy cập hoặc thay đổi trong danh sách đó. Để tạo một bộ giá trị, chúng ta phải viết các mục bên trong dấu ngoặc đơn . Giống như danh sách, chúng tôi có các phương pháp tương tự có thể được sử dụng với các bộ giá trị. Hãy xem qua một số đoạn mã để hiểu cách sử dụng bộ giá trị.

1. Tạo Tuple

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

Đầu ra

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

2. Truy cập các mục từ Tuple

#accessing first element in tuple
 
my_tuple[1]

Đầu ra

'banana'

3. Chiều dài của một Tuple

#for finding the lenght of tuple
 
len(my_tuple)

Đầu ra

3

4. Chuyển đổi Tuple sang danh sách

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

Đầu ra

list

5. Đảo ngược Tuple

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

Đầu ra

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

6. Sắp xếp một Tuple

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

Đầu ra

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

7. Xóa các phần tử khỏi Tuple

Để xóa các phần tử khỏi bộ tuple, trước tiên chúng tôi chuyển đổi bộ tuple thành một danh sách như chúng tôi đã làm trong một trong các phương pháp của chúng tôi ở trên (Điểm số 4), sau đó thực hiện theo cùng một quy trình của danh sách và loại bỏ rõ ràng toàn bộ bộ tuple, chỉ bằng cách sử dụng del tuyên bố .

TỪ ĐIỂN

Từ điển là một bộ sưu tập có nghĩa đơn giản là nó được sử dụng để lưu trữ một giá trị với một số khóa và trích xuất giá trị được cung cấp cho khóa. Chúng ta có thể coi nó như một tập hợp các cặp khóa: giá trị và mọi khóa trong từ điển được coi là duy nhất để chúng ta có thể truy cập các giá trị tương ứng tương ứng .

Một từ điển được biểu thị bằng cách sử dụng dấu ngoặc nhọn {} chứa các cặp key: value. Mỗi cặp trong từ điển được phân tách bằng dấu phẩy. Các phần tử trong từ điển không được sắp xếp theo thứ tự, trình tự không quan trọng khi chúng ta đang truy cập hoặc lưu trữ chúng.

Chúng MUTABLE có nghĩa là chúng ta có thể thêm, xóa hoặc cập nhật các phần tử trong từ điển. Dưới đây là một số ví dụ về mã để hiểu rõ hơn về từ điển trong python.

Một điểm quan trọng cần lưu ý là chúng ta không thể sử dụng một đối tượng có thể thay đổi làm khóa trong từ điển. Vì vậy, danh sách không được phép làm khóa trong từ điển.

1. Tạo từ điển

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

Đầu ra

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

Ở đây, số nguyên là khóa của từ điển và tên thành phố được kết hợp với số nguyên là giá trị của từ điển.

2. Truy cập các mục từ Từ điển

#access an item
 
print(my_dict[1])

Đầu ra

'Delhi'

3. Độ dài của từ điển

#length of the dictionary
 
len(my_dict)

Đầu ra

3

4. Sắp xếp từ điển

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

Đầu ra

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

5. Thêm các phần tử trong Từ điển

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

Đầu ra

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

6. Xóa các phần tử khỏi Từ điển

#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)

Đầu ra

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

BỘ

Set là một kiểu dữ liệu khác trong python là một tập hợp không có thứ tự không có phần tử trùng lặp. Các trường hợp sử dụng phổ biến cho một tập hợp là loại bỏ các giá trị trùng lặp và thực hiện kiểm tra tư cách thành viên. Các dấu ngoặc nhọn hoặc set()hàm có thể được sử dụng để tạo bộ. Một điều cần lưu ý là trong khi tạo một tập hợp trống, chúng ta phải sử set()dụng. Sau đó tạo ra một từ điển trống. not { }

Dưới đây là một số ví dụ mã để hiểu rõ hơn về các bộ trong python.

1. Tạo một Tập hợp

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

Đầu ra

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

2. Truy cập các mục từ một Bộ

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

Đầu ra

True

3. Chiều dài của một bộ

print(len(my_set))

Đầu ra

3

4. Sắp xếp một tập hợp

print(sorted(my_set))

Đầu ra

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

5. Thêm các phần tử trong Set

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

Đầu ra

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

6. Xóa các phần tử khỏi Set

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

Đầu ra

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

Sự kết luận

Trong bài viết này, chúng ta đã xem qua các cấu trúc dữ liệu được sử dụng phổ biến nhất trong python và cũng đã xem các phương thức khác nhau được liên kết với chúng.

Liên kết: https://www.askpython.com/python/data

#python #datastructures

Edward Jackson

Edward Jackson

1653377002

PySpark Cheat Sheet: Spark in Python

This PySpark cheat sheet with code samples covers the basics like initializing Spark in Python, loading data, sorting, and repartitioning.

Apache Spark is generally known as a fast, general and open-source engine for big data processing, with built-in modules for streaming, SQL, machine learning and graph processing. It allows you to speed analytic applications up to 100 times faster compared to technologies on the market today. You can interface Spark with Python through "PySpark". This is the Spark Python API exposes the Spark programming model to Python. 

Even though working with Spark will remind you in many ways of working with Pandas DataFrames, you'll also see that it can be tough getting familiar with all the functions that you can use to query, transform, inspect, ... your data. What's more, if you've never worked with any other programming language or if you're new to the field, it might be hard to distinguish between RDD operations.

Let's face it, map() and flatMap() are different enough, but it might still come as a challenge to decide which one you really need when you're faced with them in your analysis. Or what about other functions, like reduce() and reduceByKey()

PySpark cheat sheet

Even though the documentation is very elaborate, it never hurts to have a cheat sheet by your side, especially when you're just getting into it.

This PySpark cheat sheet covers the basics, from initializing Spark and loading your data, to retrieving RDD information, sorting, filtering and sampling your data. But that's not all. You'll also see that topics such as repartitioning, iterating, merging, saving your data and stopping the SparkContext are included in the cheat sheet. 

Note that the examples in the document take small data sets to illustrate the effect of specific functions on your data. In real life data analysis, you'll be using Spark to analyze big data.

PySpark is the Spark Python API that exposes the Spark programming model to Python.

Initializing Spark 

SparkContext 

>>> from pyspark import SparkContext
>>> sc = SparkContext(master = 'local[2]')

Inspect SparkContext 

>>> sc.version #Retrieve SparkContext version
>>> sc.pythonVer #Retrieve Python version
>>> sc.master #Master URL to connect to
>>> str(sc.sparkHome) #Path where Spark is installed on worker nodes
>>> str(sc.sparkUser()) #Retrieve name of the Spark User running SparkContext
>>> sc.appName #Return application name
>>> sc.applicationld #Retrieve application ID
>>> sc.defaultParallelism #Return default level of parallelism
>>> sc.defaultMinPartitions #Default minimum number of partitions for RDDs

Configuration 

>>> from pyspark import SparkConf, SparkContext
>>> conf = (SparkConf()
     .setMaster("local")
     .setAppName("My app")
     . set   ("spark. executor.memory",   "lg"))
>>> sc = SparkContext(conf = conf)

Using the Shell 

In the PySpark shell, a special interpreter-aware SparkContext is already created in the variable called sc.

$ ./bin/spark-shell --master local[2]
$ ./bin/pyspark --master local[s] --py-files code.py

Set which master the context connects to with the --master argument, and add Python .zip..egg or.py files to the

runtime path by passing a comma-separated list to  --py-files.

Loading Data 

Parallelized Collections 

>>> rdd = sc.parallelize([('a',7),('a',2),('b',2)])
>>> rdd2 = sc.parallelize([('a',2),('d',1),('b',1)])
>>> rdd3 = sc.parallelize(range(100))
>>> rdd = sc.parallelize([("a",["x","y","z"]),
               ("b" ["p","r,"])])

External Data 

Read either one text file from HDFS, a local file system or any Hadoop-supported file system URI with textFile(), or read in a directory of text files with wholeTextFiles(). 

>>> textFile = sc.textFile("/my/directory/•.txt")
>>> textFile2 = sc.wholeTextFiles("/my/directory/")

Retrieving RDD Information 

Basic Information 

>>> rdd.getNumPartitions() #List the number of partitions
>>> rdd.count() #Count RDD instances 3
>>> rdd.countByKey() #Count RDD instances by key
defaultdict(<type 'int'>,{'a':2,'b':1})
>>> rdd.countByValue() #Count RDD instances by value
defaultdict(<type 'int'>,{('b',2):1,('a',2):1,('a',7):1})
>>> rdd.collectAsMap() #Return (key,value) pairs as a dictionary
   {'a': 2, 'b': 2}
>>> rdd3.sum() #Sum of RDD elements 4950
>>> sc.parallelize([]).isEmpty() #Check whether RDD is empty
True

Summary 

>>> rdd3.max() #Maximum value of RDD elements 
99
>>> rdd3.min() #Minimum value of RDD elements
0
>>> rdd3.mean() #Mean value of RDD elements 
49.5
>>> rdd3.stdev() #Standard deviation of RDD elements 
28.866070047722118
>>> rdd3.variance() #Compute variance of RDD elements 
833.25
>>> rdd3.histogram(3) #Compute histogram by bins
([0,33,66,99],[33,33,34])
>>> rdd3.stats() #Summary statistics (count, mean, stdev, max & min)

Applying Functions 

#Apply a function to each RFD element
>>> rdd.map(lambda x: x+(x[1],x[0])).collect()
[('a' ,7,7, 'a'),('a' ,2,2, 'a'), ('b' ,2,2, 'b')]
#Apply a function to each RDD element and flatten the result
>>> rdd5 = rdd.flatMap(lambda x: x+(x[1],x[0]))
>>> rdd5.collect()
['a',7 , 7 ,  'a' , 'a' , 2,  2,  'a', 'b', 2 , 2, 'b']
#Apply a flatMap function to each (key,value) pair of rdd4 without changing the keys
>>> rdds.flatMapValues(lambda x: x).collect()
[('a', 'x'), ('a', 'y'), ('a', 'z'),('b', 'p'),('b', 'r')]

Selecting Data

Getting

>>> rdd.collect() #Return a list with all RDD elements 
[('a', 7), ('a', 2), ('b', 2)]
>>> rdd.take(2) #Take first 2 RDD elements 
[('a', 7),  ('a', 2)]
>>> rdd.first() #Take first RDD element
('a', 7)
>>> rdd.top(2) #Take top 2 RDD elements 
[('b', 2), ('a', 7)]

Sampling

>>> rdd3.sample(False, 0.15, 81).collect() #Return sampled subset of rdd3
     [3,4,27,31,40,41,42,43,60,76,79,80,86,97]

Filtering

>>> rdd.filter(lambda x: "a" in x).collect() #Filter the RDD
[('a',7),('a',2)]
>>> rdd5.distinct().collect() #Return distinct RDD values
['a' ,2, 'b',7]
>>> rdd.keys().collect() #Return (key,value) RDD's keys
['a',  'a',  'b']

Iterating 

>>> def g (x): print(x)
>>> rdd.foreach(g) #Apply a function to all RDD elements
('a', 7)
('b', 2)
('a', 2)

Reshaping Data 

Reducing

>>> rdd.reduceByKey(lambda x,y : x+y).collect() #Merge the rdd values for each key
[('a',9),('b',2)]
>>> rdd.reduce(lambda a, b: a+ b) #Merge the rdd values
('a', 7, 'a' , 2 , 'b' , 2)

 

Grouping by

>>> rdd3.groupBy(lambda x: x % 2) #Return RDD of grouped values
          .mapValues(list)
          .collect()
>>> rdd.groupByKey() #Group rdd by key
          .mapValues(list)
          .collect() 
[('a',[7,2]),('b',[2])]

Aggregating

>> seqOp = (lambda x,y: (x[0]+y,x[1]+1))
>>> combOp = (lambda x,y:(x[0]+y[0],x[1]+y[1]))
#Aggregate RDD elements of each partition and then the results
>>> rdd3.aggregate((0,0),seqOp,combOp) 
(4950,100)
#Aggregate values of each RDD key
>>> rdd.aggregateByKey((0,0),seqop,combop).collect() 
     [('a',(9,2)), ('b',(2,1))]
#Aggregate the elements of each partition, and then the results
>>> rdd3.fold(0,add)
     4950
#Merge the values for each key
>>> rdd.foldByKey(0, add).collect()
[('a' ,9), ('b' ,2)]
#Create tuples of RDD elements by applying a function
>>> rdd3.keyBy(lambda x: x+x).collect()

Mathematical Operations 

>>>> rdd.subtract(rdd2).collect() #Return each rdd value not contained in rdd2
[('b' ,2), ('a' ,7)]
#Return each (key,value) pair of rdd2 with no matching key in rdd
>>> rdd2.subtractByKey(rdd).collect()
[('d', 1)1
>>>rdd.cartesian(rdd2).collect() #Return the Cartesian product of rdd and rdd2

Sort 

>>> rdd2.sortBy(lambda x: x[1]).collect() #Sort RDD by given function
[('d',1),('b',1),('a',2)]
>>> rdd2.sortByKey().collect() #Sort (key, value) ROD by key
[('a' ,2), ('b' ,1), ('d' ,1)]

Repartitioning 

>>> rdd.repartition(4) #New RDD with 4 partitions
>>> rdd.coalesce(1) #Decrease the number of partitions in the RDD to 1

Saving 

>>> rdd.saveAsTextFile("rdd.txt")
>>> rdd.saveAsHadoopFile("hdfs:// namenodehost/parent/child",
               'org.apache.hadoop.mapred.TextOutputFormat')

Stopping SparkContext 

>>> sc.stop()

Execution 

$ ./bin/spark-submit examples/src/main/python/pi.py

Have this Cheat Sheet at your fingertips

Original article source at https://www.datacamp.com

#pyspark #cheatsheet #spark #python

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