search
HomeBackend DevelopmentPython TutorialApplication of data structures and algorithms in Python (with examples)

The content this article brings to you is about the application of data structures and algorithms in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.

Question 1

Now there is a tuple or sequence containing N elements. How to decompress the values ​​​​in it and assign them at the same time? Give N variables?

Solution

Any sequence (iterable object) can be unpacked and assigned to multiple variables with a simple assignment statement. The premise is that the number of variables and the number of sequence elements must be consistent.

In [3]: p = (4,5)

In [4]: x,y = p

In [5]: x
Out[5]: 4

In [6]: y
Out[6]: 5

In [7]: data = ['ACME', 50, 91.1, (2012, 12, 21)]

In [8]: name, shares, price, date = data

In [9]: name
Out[9]: 'ACME'

In [10]: shares
Out[10]: 50

In [11]: date
Out[11]: (2012, 12, 21)

If the number of variables and the number of sequence elements do not match, an exception will be generated.

In [12]: p = (x,5)

In [13]: a,b,c = p
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-f5a6e296606a> in <module>()
----> 1 a,b,c = p

ValueError: not enough values to unpack (expected 3, got 2)</module></ipython-input-13-f5a6e296606a>

This unpacking assignment can be used on any iterable object, not just lists or tuples, but also strings, file objects, iterators and generators.

In [14]: A = 'hello'

In [15]: a,b,c,d,e = A

In [16]: a
Out[16]: 'h'

In [17]: b
Out[17]: 'e'

In [18]: c
Out[18]: 'l'

In [19]: d
Out[19]: 'l'

In [20]: e
Out[20]: 'o'

In [21]: a,b,c,d,e
Out[21]: ('h', 'e', 'l', 'l', 'o')

For those who only want to decompress part of the sequence and discard some of the values, just use some unnecessary variable names to occupy the sequence elements at the corresponding positions.

In [22]: data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]

In [23]: _, shares, price, _ = data

In [24]: shares
Out[24]: 50

In [25]: price
Out[25]: 91.1

Question 2

If the number of elements of an iterable object exceeds the number of variables, a ValueError will be thrown. So how can we extract N elements from this iterable object?

Solution

Python’s asterisk expression can solve this problem. For example, you are studying a course, and at the end of the semester, you want to calculate the average grade of homework assignments, but exclude the first and last grades. If there were only four fractions, you might just go ahead and simply assign them manually, but what if there were 24? At this time, the asterisk expression comes in handy:
In the function call, the matching is simply based on the position of the variable name, but the use of name=value tells Python to still match according to the variable name. These are called keywords parameter. Using *sequence or **dict in the call allows us to encapsulate any number of position-related or keyword objects in a sequence or dictionary accordingly, and pass them to the function , unpack them into separate, single parameters.

In [26]: def drop_first_last(grades):
   ....:     first,*middle,last = grades
   ....:     return avg(middle)

The above is the detailed content of Application of data structures and algorithms in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version