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 use python named tuples and deductions

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

Share

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

Today, the editor will share with you the relevant knowledge points about how to use python naming tuples and derivation. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

I. named tuples

On the basis of python, when we learn tuples, the elements inside the tuple are all valued by index. But this kind of value method is not friendly, so we introduce the method of naming tuples for dictionary values, which takes up less memory than dictionary storage. If the data does not need to change, you can use named tuples instead of dictionaries.

General tuple value method:

Info = ("flora", 28, "female") name = 0age = 1gender = 2print (info[ name]) # get name print (info[ age]) # get age print (infogender) # get gender

Named tuple method:

# namedtuple: receives two parameters: the first parameter is the name of the created type The second parameter is the list from collections import namedtupleinfo = namedtuple ("info_key", ["name", "age", "gender"]) info_01 = info ("flora", 28, "female") print (info_01.name) # get name print (info_01.age) # get age print (info_01.gender) # get gender print (info_01) # print result: info_key (name='flora', age=28) Gender=' 2. Application in automated testing scenarios

We read the use case data from excel. The first row of header is key, and the value of each row is value. If stored as a dictionary format, the format is as follows:

Case = [{"case_id": 1, "case_title": "normal login", "data": "test", "expected": "pass"}, {"case_id": 2, "case_title": "login failed", "data": "test", "expected": "pass"},]

We can store it as a named tuple, as follows:

# namedtuple: receives two parameters: the first parameter is the name of the created type The second parameter is the list from collections import namedtuplecase = [{"case_id": 1, "case_title": "normal login", "data": "test01", "expected": "pass"}, {"case_id": 2, "case_title": "login failed", "data": "test02", "expected": "pass"},] cases = namedtuple ("case") Case [0] .keys () for i in case: result = cases (* i.values ()) print (result.data) # print result: test01 test02 ternary and ternary operators

The ternary operator in python is equivalent to the ternary operator in java.

Basic grammar

The result of the execution of the condition if filter condition else condition is not true

Practical application

For example, we want to write a Python program that enters two numbers, compares their sizes, and outputs the larger of them. Compared with the conventional writing method, the ternary operator writing method is more concise and clear.

Conventional writing:

X = int (input ("please enter the first positive integer:") y = int (input ("Please enter the second positive integer:") if x = = y: print ("the larger number is:", x) elif x > y: print ("the larger number is:", x) else: print ("the larger number is:", y)

Ternary operator writing:

X = int (input ("Please enter the first positive integer:") y = int (input ("Please enter the second positive integer:") print ("larger number is: {}" .format (x if x > y else y))

Extension: nesting of ternary operators

The Python ternary operator supports nesting, which allows for more complex expressions. Pay attention to the pairing of if and else when nesting.

For example, we need to judge the relationship between two numbers.

Conventional writing:

A = int (input ("please enter a:") b = int (input ("please enter b:") if a > b: print ("an is greater than b") else: if a

< b: print("a小于b") else: print("a等于b") 三目运算符嵌套写法: a = int(input("请输入a:"))b = int(input("请输入b:"))print("a大于b") if a >

B else (print ("a less than b") if a < b else print ("an equals b") 4. Deductive comprehensions (also called analytical formula) is a unique feature of python. Deduction is that you can build a new data sequence from one data sequence. The role of deduction: to generate data quickly.

List derivation

General list derivation

Basic syntax: [iterate through the content added to the list each time for x in xxx]

Example: outputs a list of 0-100 numbers.

Conventional writing:

Li = [] for i in range (101): li.append (I) print (li)

Deductive writing:

Li = [i for i in range (101)] print (li)

List-driven nested if

Basic syntax: [for x in xxx if filter criteria for each traversal of content added to the list]

Example: outputs a list of even numbers from 0 to 100.

Conventional writing:

Li = [] for i in range (101): if I% 2 = 0: li.append (I) print (li)

Deductive writing:

Li = [i for i in range (101) if I% 2 = = 0] print (li)

List derivation combined with trinomial operator

Basic syntax: [if filter condition else condition traverses the content added to the list every time for x in xxx]

Example: 0-100 numbers. Return even 0 if it is even, and odd 1 if it is odd.

Conventional writing:

Li = [] for i in range: if I% 2 = 0: li.append ("even 0") else: li.append ("odd 1") print (li)

List deduction + trinomial operator:

Li = ["even 0" if I% 2 = 0 else "Odd 1" for i in range (101)] print (li) 5. Dictionary derivation

Basic syntax: {key: the expression that gets the key value}

Example: there is a list li that converts it into data in the dictionary format of an element whose subscript is key and whose value is in the dictionary format of the element.

Conventional writing:

Li = ["id", "title", "url", "data", "expected"] dic = {} for I, j in enumerate (li): dic [I] = jprint (dic)

Dictionary-derived writing:

Li = ["id", "title", "url", "data", "expected"] dic = {I: j for i, j in enumerate (li)} print (dic) these are all the contents of the article "how to use python named tuples and deductions". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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