Usage of namedtuple function in python analysis
【Related recommendations: Python3 video tutorial】
Source code explanation:
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) """
Grammar structure:
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
- typename: represents the name of a newly created tuple.
- field_names: is the content of the tuple, which is a list-like ['x', 'y']
named tuple, making the tuple It can be accessed using key like a list (and can also be accessed using index).
collections.namedtuple is a factory function that can be used to construct a tuple with field names and a named class.
Creating a named tuple requires two parameters, one is the class name, and the other is the name of each field of the class.
The data stored in the corresponding field must be passed into the constructor in the form of a series of parameters (note that the tuple constructor only accepts a single iterable object).
Named tuples also have some unique properties of their own. The most useful: class attributes _fields, class method _make(iterable) and instance method _asdict().
Sample code 1:
from collections import namedtuple # 定义一个命名元祖city,City类,有name/country/population/coordinates四个字段 city = namedtuple('City', 'name country population coordinates') tokyo = city('Tokyo', 'JP', 36.933, (35.689, 139.69)) print(tokyo) # _fields 类属性,返回一个包含这个类所有字段名称的元组 print(city._fields) # 定义一个命名元祖latLong,LatLong类,有lat/long两个字段 latLong = namedtuple('LatLong', 'lat long') delhi_data = ('Delhi NCR', 'IN', 21.935, latLong(28.618, 77.208)) # 用 _make() 通过接受一个可迭代对象来生成这个类的一个实例,作用跟City(*delhi_data)相同 delhi = city._make(delhi_data) # _asdict() 把具名元组以 collections.OrderedDict 的形式返回,可以利用它来把元组里的信息友好地呈现出来。 print(delhi._asdict())
Running result:
Sample code 2:
from collections import namedtuple Person = namedtuple('Person', ['age', 'height', 'name']) data2 = [Person(10, 1.4, 'xiaoming'), Person(12, 1.5, 'xiaohong')] print(data2) res = data2[0].age print(res) res2 = data2[1].name print(res2)
Running result:
##Sample code 3:
from collections import namedtuple card = namedtuple('Card', ['rank', 'suit']) # 定义一个命名元祖card,Card类,有rank和suit两个字段 class FrenchDeck(object): ranks = [str(n) for n in range(2, 5)] + list('XYZ') suits = 'AA BB CC DD'.split() # 生成一个列表,用空格将字符串分隔成列表 def __init__(self): # 生成一个命名元组组成的列表,将suits、ranks两个列表的元素分别作为命名元组rank、suit的值。 self._cards = [card(rank, suit) for suit in self.suits for rank in self.ranks] print(self._cards) # 获取列表的长度 def __len__(self): return len(self._cards) # 根据索引取值 def __getitem__(self, item): return self._cards[item] f = FrenchDeck() print(f.__len__()) print(f.__getitem__(3))
Run result:
Example code 4:
from collections import namedtuple person = namedtuple('Person', ['first_name', 'last_name']) p1 = person('san', 'zhang') print(p1) print('first item is:', (p1.first_name, p1[0])) print('second item is', (p1.last_name, p1[1]))
Run Result:
Sample code 5: [_make creates an instance from an existing sequence or iteration]
from collections import namedtuple course = namedtuple('Course', ['course_name', 'classroom', 'teacher', 'course_data']) math = course('math', 'ERB001', 'Xiaoming', '09-Feb') print(math) print(math.course_name, math.course_data) course_list = [ ('computer_science', 'CS001', 'Jack_ma', 'Monday'), ('EE', 'EE001', 'Dr.han', 'Friday'), ('Pyhsics', 'EE001', 'Prof.Chen', 'None') ] for k in course_list: course_i = course._make(k) print(course_i)
Run result:
Sample code 6: [_asdict returns a new ordereddict, mapping field names to corresponding values]
from collections import namedtuple person = namedtuple('Person', ['first_name', 'last_name']) zhang_san = ('Zhang', 'San') p = person._make(zhang_san) print(p) # 返回的类型不是dict,而是orderedDict print(p._asdict())
Run result:
Sample code 7: [_replace returns a new instance and replaces it with Replace the specified field with the new value】
from collections import namedtuple person = namedtuple('Person', ['first_name', 'last_name']) zhang_san = ('Zhang', 'San') p = person._make(zhang_san) print(p) p_replace = p._replace(first_name='Wang') print(p_replace) print(p) p_replace2 = p_replace._replace(first_name='Dong') print(p_replace2)
Running result:
【 _fields returns field name]from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
zhang_san = ('Zhang', 'San')
p = person._make(zhang_san)
print(p)
print(p._fields)
[Using fields can Combine two namedtuples]from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
print(person._fields)
degree = namedtuple('Degree', 'major degree_class')
print(degree._fields)
person_with_degree = namedtuple('person_with_degree', person._fields + degree._fields)
print(person_with_degree._fields)
zhang_san = person_with_degree('san', 'zhang', 'cs', 'master')
print(zhang_san)
【 field_defaults】from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'], defaults=['san'])
print(person._fields)
print(person._field_defaults)
print(person('zhang'))
print(person('Li', 'si'))
[namedtuple is a class, so Functions can be changed through subclasses]from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(4, 5)
print(p)
class Point(namedtuple('Point', ['x', 'y'])):
__slots__ = ()
@property
def hypot(self):
return self.x + self.y
def hypot2(self):
return self.x + self.y
def __str__(self):
return 'result is %.3f' % (self.x + self.y)
aa = Point(4, 5)
print(aa)
print(aa.hypot)
print(aa.hypot2)
##Sample code 12:
from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(11, 22) print(p) print(p.x, p.y) # namedtuple本质上等于下面写法 class Point2(object): def __init__(self, x, y): self.x = x self.y = y o = Point2(33, 44) print(o) print(o.x, o.y)
##[Related recommendations:
Python3 video tutorial 】
The above is the detailed content of Usage of namedtuple function in python analysis. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

This article discusses the DDoS attack detection method. Although no direct application case of "DebianSniffer" was found, the following methods can be used for DDoS attack detection: Effective DDoS attack detection technology: Detection based on traffic analysis: identifying DDoS attacks by monitoring abnormal patterns of network traffic, such as sudden traffic growth, surge in connections on specific ports, etc. This can be achieved using a variety of tools, including but not limited to professional network monitoring systems and custom scripts. For example, Python scripts combined with pyshark and colorama libraries can monitor network traffic in real time and issue alerts. Detection based on statistical analysis: By analyzing statistical characteristics of network traffic, such as data

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.
