Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Python functional programming strings and tuples, function classification and higher-order functions

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to understand Python functional programming strings and tuples and function classification and high-order functions, I believe that many inexperienced people do not know what to do. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Strings in functional programming

In functional programming, Python strings are often used because they are immutable data structures.

The string itself is an object and has many object methods, which is different from the use of functions in common sense, such as the following code

My_str = "xiangpica" print (my_str.upper ()) print (len (my_str.upper ())

Among them, the usage of len () function is called pre-writing, while my_str.upper () is called post-writing, which can easily cause the understanding problem of functional programming, so it is necessary to solve this problem systematically.

If the above code can be changed to len (upper (my_str)), it becomes relatively easy to understand.

# Type Text is the alias of str from typing import Textmy_str = "xiangpica" def upper (str: Text)-> Text: return str.upper () print (upper (my_str)) print (len (upper (my_str)

The above code redefines a pre-usage function, upper, to solve the consistency problem in functional programming, which often occurs in subsequent code.

Invariant type tuple

In addition to strings, another immutable data type in Python is tuples, which are divided into normal tuples and named tuples.

Declaration and access of ordinary tuples

In the previous article, the basic knowledge of tuples has been explained, you can go to a little review, and then enter the study of this article.

Take a look at the code before judging whether it is understandable or not.

From typing import Tuple, Text, CallableLANGUAGE = Tuple [Text, Text, Text] python: Callable [[LANGUAGE], Text] = lambda languages: languages [1] items = ("c", "python", "js") a = python (items) print (a)

The above code defines a new type, LANGUAGE, which is a tuple with three elements.

The python type annotation is Callable [[LANGUAGE], Text], that is, its parameter is of type LANGUAGE and the return value is of type of string.

Note that the addition of the typing module will not affect the operation of the program will not report formal errors, only as a type check to prevent run-time parameters, return value types do not match, developers consult.

In addition to the above, you can also use named tuples.

From collections import namedtupleLanguage = namedtuple ("Language", ("name1", "name2", "name3")) l = Language ("c", "python", "js") print (l) print (l.name1)

Or use the NamedTuple of the typing module directly.

From typing import NamedTuple, Textclass Language (NamedTuple): name: Text description: Textl = Language ("C", "C language") print (l) print (l.name) print (l.description) functional classification

There are two main categories of functions:

Scalar function: the return result of the function is a value

Set function: the result of a function is an iterative set.

Collection functions can also be subdivided:

Specification / accumulation function: accumulate the elements in the set and get a value

Mapping function: apply a scalar function to each element of several, and finally get a new set of the same length as the original set

Filter function: apply a scalar function to each element, retain part of it, and get a subset.

With the above concepts, the understanding of functional programming can be further.

Comparative study of any (), all (), len () and sum ()

Any and all functions belong to the specification function, the operation is called Boolean specification, that is, a set of elements reduced to True or False,all requires that all values are True,any as long as one value is True.

Len and sum are also reduction functions, which represent the number and total value of all values in the calculated set, respectively.

Zip (), reversed (), enumerate ()

The zip function can cross-combine the data between multiple iterable objects or sequences, that is, the iterable objects of n elements are converted into n tuples, and then return a generator.

If the zip function has no input arguments, it returns an empty list [].

A = zip () print (list (a))

The reversed function is used to change the sequence order, that is, to reverse the sequence.

The enumerate function takes the subscript value of a sequence or iterable object, and translating it into a conceptual description is to map the iterable object to a binary sequence (with a sequence number). In each binary sequence, the first element is the subscript value, and the second element is the value itself.

Higher order function

Learning Python functional programming can not avoid the study of higher-order functions, which take the function as the parameter or the return value as the function.

The functions max and min ()

The above two functions are specification functions, that is, the input is a set, the output is a single value, the main purpose is to find the extreme value.

In general, when learning, the two can be regarded as ordinary functions, but also can be used for higher-order functions, mainly for the difference of parameter positions.

The simplest usage is:

Max_num = max (1,2,3,4) min_num = min (1,2,3,4) print (max_num) print (min_num)

Next is the implementation of its high-order function model, customizing the comparison rules.

# first, compare string length max_num = max ("a", "abc", "ceda", "aaaaa", key=lambda x: len (x)) min_num = min ("a", "abc", "ceda", "aaaaa", key=lambda x: len (x)) print (max_num) print (min_num) # second way of writing Compare string length max_num = max (["a", "abc", "ceda", "aaaaa"], key=lambda x: len (x)) min_num = min (["a", "abc", "ceda", "aaaaa"], key=lambda x: len (x) print (max_num) print (min_num)

The key of the above code is optional, and the default value is None.

Map function

The map function is used to map one collection to another, for example, to convert each item in a list of strings to an integer.

Data = ["1", "2", "3"] print (map (int, data)) print (list (map (int, data))

The meaning of the code map (int, data) is to apply the int function to every item in data.

The first argument of the map function can also be replaced with lambda.

Data = ["1", "2", "3"] print (map (lambda x: int (x), data)) print (list (int, data)) filter function

The filter function is mainly used to apply a * * decision function (predicate function) * * to each element of the set, and finally get the result set that satisfies the decision function. The test code is as follows:

Data = [1,3,5,7,9] print (filter (lambda x: X > 3, data)) print (list (lambda x: X > 3, data)) sorted function

The sorted function also supports higher-order function key parameter customization rules.

Result = sorted (["afghsss", "abc", "ceda", "aaaaa"], key=lambda x: len (x) print (result) different efficiency problems of the same demand

The map function, the generator expression, and the generator function with iterator are each tested with a list of 100 million more data.

Import timedef demo (x): return x * 2def demo1 (f, l): for x in l: yield f (x) my_list = list (range (1, 10000000)) start = time.perf_counter () # map (lambda x: X * 2, my_list) # Program running time 3.904999999998493e-06# (demo (x) for x in my_list) # Program running time 6.310000000009364e-06demo1 (demo My_list) # Program time 5.1070000000041915e-06cost_time = time.perf_counter ()-startprint ("Program time consuming", cost_time)

The result is that map is the fastest, so we are done with it.

After reading the above, have you mastered how to understand Python functional programming strings and tuples and how to classify functions and higher-order functions? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report