current position:Home>Python Complete Guide -- tuple conversion array
Python Complete Guide -- tuple conversion array
2022-01-30 20:43:28 【Stone sword】
In this article , We will learn how to stay Python in hold Tuples transformation number Group .Python It's a great programming language . From the day it appeared , Its popularity is increasing day by day .Python How its unique advantages make it popular .
About Python
- An open source project
- Python Creator Guido Von Rossum Mr. made it an open source project when developing . He believes that keeping its free contribution will add more functions to it . More Than This , Different developers can also make it cross platform , And develop... For other fields . as time goes on , His idea finally succeeded .
- Developers are now contributing to it , Various modules are helping learners learn new concepts very easily .
- Huge library support
- Thanks to the contribution of open source , Various modules and libraries can be used . Each library is an independent task .
- These libraries are easy to add to python Environment .pip package (Package Installer for Python) Make it simple .
- Great developer support
- about Python, Developers are all over the world .
- They keep sending more and more advanced code , Make this project a better platform for coders .
- Optional fields
- There are various fields to choose from . machine learning , Data Science , Artificial intelligence , Network scraping , Network development , The Internet of things and cloud computing Some of these areas are .
- Core applications also include software development .
- Easy to learn and understand
- Python It's easy to learn and understand . It's very simple , One can complete basic arithmetic and input operations in one day .
- It is an object-oriented multi-purpose programming language , With the simplest class implementation .
Python Arrays and lists in
Considering that we need to create ten integer variables for some programming related work . We need to make some statements , obviously , This will include ten additional lines of code . Making such code is a tedious job . So we have arrays to solve this problem .
Python The array or list in is one of the most basic data structures to learn . They are a collection of elements belonging to one or more data types . The idea behind arrays is , We can access these elements multiple times . This also reduces many lines of code , And eliminates the creation of additional variables .
Python The difference between list and array in
list | array |
Elements with different data types . | Elements that contain a single data type . |
Iteratable through a loop | Iteratable through a loop |
It often operates in a one-dimensional model | It often operates in one or more dimensions . |
source -Python List vs Array
When everyone is confused between the two , The main problem arises . therefore , To make it clear , We will use code to apply
stay Python Declare a list in
Let us in Python Declare a list in
Code
list1 = [23, 34, 12, 22] # declaring a list
print(list1) # printing the list on the screen
Copy code
Output
List output
We can edit the list in various ways . These operations include
- Add new elements
- Remove elements
- Multiply element by external element .
1. Add a new element
**append()** Method to add a new element at the end of the list . This function takes the last element we need to add as a parameter .
Code
list1 = [11, 34, 23, 33, 4]
list1.append(2) # adds 2 at the end
# Output :- [11, 34, 23, 33, 4, 2]
Copy code
We can also use the concept of index to edit the list . An index is a positional number assigned to each element in a list and array . It starts from left to right and from right to left .
Code
list1 = [23, 2, 4, 44]
# 0 1 2 3 positive indexing starts from left to right
# -4 -3 -2 -1 negative indexing starts from right to left
Copy code
To access them , We need to call the list with this index number inside square brackets . In the following example , We will access the third element . remember , The index of positive numbers starts from 0 Start , Until n-1.
Code
list1 = [11, 34, 23, 33, 4]
print(list1[2])
# Output :- 23
Copy code
explain
- Index from 0 Start , from 0 To 2 The count is 3, Its output is 23. therefore , To access the third element , We need to invoke it in square brackets. 2.
- In the second line of code , We change the second by using the same properties 2 Elements of position .
2. Delete new elements
The main purpose of adding new elements is good , however , When we need to remove them from the list , There are also some operations . There are several functions that can help us delete objects .
- **clear()** Remove all elements from the list of functions , And return an empty list
- **pop()** The function takes an integer, index number, as an argument , Delete the element related to the index position .
- **remove()** Function removes the element we need to give it as an argument from the list .
Code
list1 = [23, 89, 2, 3, -1, 12]
list1.clear() # deleting each element from the list
print(list1)
list1 = [23, 89, 2, 3, -1, 12]
list1.pop(4) # deleting the element from 4th index of the list
print(list1)
list1 = [23, 89, 2, 3, -1, 12]
list1.remove(-1) # search and remove the specified element from the list
print(list1)
Copy code
Output
The list of operations
What is? Python In the array ?
Python There's a separate one ** Array operation library .** When we use Array When the module , We can feel something C Language programming experience .
We know that in this data structure , We can only store elements of the same data type . therefore , There are some special Unicode Character supply python The compiler recognizes the type of element or object in it .
To declare an array , There are a series of rules .array() The function requires some parameters . They are specific to specific data types .
The type of code | C- type | Python type |
‘b’ | Signed characters | Integers |
‘B’ | An unsigned character | Integers |
‘u’ | character | An unsigned character |
‘h’ | Signed short code | Integers |
‘H’ | Unsigned short code | Integers |
‘i’ | Signed short code | Integers |
‘I’ | Unsigned decimal | Integers |
‘l’ | Signed long | Integers |
‘L’ | Unsigned long | Integers |
‘q’ | Signed long | Integers |
‘Q’ | Unsigned long string | Integers |
‘f’ | Floating point numbers | float |
‘d’ | dual | float |
Appoint C Type special characters are used to make things clearer . These types represent the data types of the elements that exist in this particular array . The above code is some basic implementation methods .
Code
from array import *
int_array = array('i', [1, 4, 55, 51, -2])
print('\n Integer array: ',int_array)
char_array = array('u', ['a', 'b', 'c', 'd'])
print('\n Character array: ', char_array)
float_array = array('f', [2.2, 4.3, -1.2, 9.0])
print('\n Floating point array: ', float_array, '\n')
Copy code
Output
Array operation
Array to list conversion
Other methods such as append(), pop() And so on are also applicable to this module . Through this link See more on the document page . Other special features include converting arrays to normal lists --array.tolist().
Code :
from array import *
char_array = array('u', ['a', 'b', 'c', 'd'])
print('\n Character array: ', char_array)
print('Data type: ', type(char_array))
char_array = char_array.tolist()
print('\n','Converted array: ', char_array)
print('Data type: ', type(char_array))
Copy code
Array to list conversion
Be careful : In code type() Function returns the data type of the variable . through Over it , We check the data type of the array and convert the array to a list .
What is? Python Elements in ?
Python One of the most basic data structures in is ** Primitives **. Primitives are immutable data structures . We put the elements in parentheses , Separate them with commas . Once we create an element , There is no way to change or edit it directly .
Code
tup = (3, 1, 2, 4, 5, 6) # declaration of a tuple
print(tup) # printing it on the screen
# output - (3, 1, 2, 4, 5, 6)
Copy code
1. Retrieve elements in tuples
We can use Index method Access elements in tuples . Like a list , Elements in tuples are assigned index numbers .
tup = (2, 34, 1, -1, -4, 3)
print(tup[3])
print(tup[4])
print(tup[-1])
Copy code
Tuple operation
Here we start with the fourth of the tuple 、 Extract the elements at the fifth and last positions .
Convert tuples into arrays and other data structures
Python Several functions and modules are provided to convert them into other data structures . Literally , They are simple lines of code .
Convert a tuple to an array
We will introduce two methods here . The first is to use Array module , The second is to use NumPy modular .
Use the array module to convert tuples into arrays
Before , The array module helps us declare pure arrays . however , We can also use it for conversion purposes . therefore , To make it clear , Let's use code to understand .
from array import *
tup = (23, 98, 3, -2, -4, 11)
print('\n tuple: ', tup)
conv_tup = array('i', tup)
print('\n Converted tuple to an array: ',conv_tup, '\n')
Copy code
Use array module for conversion
explain
- Import array module .
- Declare a tuple . Print it on the screen .
- Then we use the array function . In this function The type of code by **'i' Of ** character . This will transform the tuple into an array of integers . In the next parameter , We separate our tuples with commas .
- Print the array on the screen .
Use Numpy The module converts tuples into arrays
Numpy- Numerical Python Is a very good library of array related operations . It is the developer's choice for complex mathematical calculation .
For this purpose , We use... In this library **array()** Method . This method converts tuples to NumPy Array , For our use .
Code
import numpy as np
tup = (23, 98, 3, -2, -4, 11)
print('\n tuple: ', tup)
print('Data type', type(tup))
conv_tup = np.array(tup)
print('\n Converted tuple to an array: ',conv_tup)
print('Data type', type(conv_tup),'\n')
Copy code
Output
Use Numpy Module conversion
explain
- Import NumPy modular .
- Declare tuples and print them on the screen .
- Use type() Print data type .
- Declare a variable conv_tup And call **np.array()** Method , Where tuples are used as parameters .
- Print the converted tuple and its data type on the screen , To confirm the conversion result .
Convert tuples to a list
Code
tup = (2, 34, 2. -1, 9, 0) # declare a tuple
new_tup = list(tup) # converts tuple into list
print(new_tup)
# Output = [2, 34, 2. -1, 9, 0)]
Copy code
explain
- First , We declare a tuple as tup.
- then , Let's build a variable new_tup, Call again **list()** function , Give our tuple a parameter inside .
- It converts it into a normal list .
- Then we print it on the screen
Conclusion
therefore , Here we end python Topic of conversion from metagroup to array . These codes are very simple to implement , It's also easy to learn . therefore , Please trace each line of code and understand its function . This article also removes the concepts of lists and tuples .
copyright notice
author[Stone sword],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201302043066493.html
The sidebar is recommended
- Introduction to python (IV) dynamic web page analysis and capture
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
guess what you like
-
This is what you should do to quickly create a list in Python
-
On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
-
Python OpenCV image area contour mark, which can be used to frame various small notes
-
How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
-
Initial Python tuple
-
Introduction to Python urllib module
-
Advanced Python Basics: from functions to advanced magic methods
-
Python Foundation: data structure summary
-
Python Basics: from variables to exception handling
-
Python notes (22): time module and calendar module
Random recommended
- Python notes (20): built in high-order functions
- Python notes (17): closure
- Python notes (18): decorator
- Python notes (16): generators and iterators
- Python notes (XV): List derivation
- Python tells you what timing attacks are
- Python -- file and exception
- [Python from introduction to mastery] (IV) what are the built-in data types of Python? Figure out
- Python code to scan code to pay attention to official account login
- [algorithm learning] 1221 Split balanced string (Java / C / C + + / Python / go / trust)
- Python notes (22): errors and exceptions
- Python has been hidden for ten years, and once image recognition is heard all over the world
- Python notes (21): random number module
- Python notes (19): anonymous functions
- Use Python and OpenCV to calculate and draw two-dimensional histogram
- Python, Hough circle transformation in opencv
- A library for reading and writing markdown in Python: mdutils
- Datetime of Python time operation (Part I)
- The most useful decorator in the python standard library
- Python iterators and generators
- [Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods
- Does Python have a, = operator?
- Go through the string common sense in Python
- Fanwai 4 Handling of mouse events and solutions to common problems in Python opencv
- Summary of common functions for processing strings in Python
- When writing Python scripts, be sure to add this
- Python web crawler - Fundamentals (1)
- Pandas handles duplicate values
- Python notes (23): regular module
- Python crawlers are slow? Concurrent programming to understand it
- Parameter passing of Python function
- Stroke tuple in Python
- Talk about ordinary functions and higher-order functions in Python
- [Python data acquisition] page image crawling and saving
- [Python data collection] selenium automated test framework
- Talk about function passing and other supplements in Python
- Python programming simulation poker game
- leetcode 160. Intersection of Two Linked Lists (python)
- Python crawler actual combat, requests module, python to grab the beautiful wallpaper of a station
- Fanwai 5 Detailed description of slider in Python opencv and solutions to common problems