程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The use of python3 lists, tuples, and dictionaries in data structures

編輯:Python

list

Stack use of list

Stack is a single element in data, last in first out , Push the top of the stack , The top of the stack
for example :

>>> myStack = [1, 2, 3, 4.5];
>>> myStack.append(66);
>>> myStack.append(77);
>>> myStack.append(88);
# The output is as follows 
>>> myStack;
[1, 2, 3, 4.5, 66, 77, 88]
>>> myStack.pop();
88
>>> myStack.pop();
77
>>> myStack;
[1, 2, 3, 4.5, 66]

It can be seen that append Every time you add an element to the end of the list , pop Delete the last element each time and return , Conform to the definition of stack

The queue of the list uses

queue , That is, the elements in the data are last in and last out , The element that enters the queue first leaves the queue first
Examples are as follows :

>>> from collections import deque
>>> myquence = deque(["a", 'b', "c"]);
>>> myquence.append("dd");
>>> myquence.append("ee");
>>> myquence;
deque(['a', 'b', 'c', 'dd', 'ee'])
>>> myquence.popleft();
'a'
>>> myquence.popleft();
'b'
>>> myquence
deque(['c', 'dd', 'ee'])

But this method is not a linked list after all , After moving the first element, all subsequent elements will move , And the larger the amount of data, the longer the time it takes
This is related to Java similar , alike Java It is also recommended to perform this operation Use LinkedList That is, the sub implementation class of the linked list , To speed up

List derivation

Do certain operations on each element of a basic list element, and finally get a new result set .
Every list derivation is in for Followed by an expression , Then there are zero to many for or if Clause . The return result is based on the expression from the following for and if The list generated in the context . If you want the expression to derive a tuple , You have to use brackets .

Example 1: For example, multiply each element in the array 2 And then get new results :

>>> list1 = [1, 2, 3];
>>> [x*3 for x in list1];
[3, 6, 9]
>>> list1;
[1, 2, 3]
>>>

Example 2: Do array nesting , Multiply each element and put it into a new one with the original number [] in

>>> list1 = [1, 2, 3];
>>> [[x, x**2] for x in list1];
[[1, 1], [2, 4], [3, 9]]
>>> list1;
[1, 2, 3]
>>>

Such processing is similar to Java Medium foreach as well as lambda How to operate

I am It is understood as follows Of :
No matter how it is written internally Look first for in The content of , namely Understand as right first in Each element in the following list x do for The previous operation is finally put into Whole [] As an element , After traversing all elements, the result is the result set of its own derivation ;

Call a method one by one An example of :

>>> list1 = [" daw ", "lcd ", "11 56 "];
>>> [item.strip() for item in list1]
['daw', 'lcd', '11 56']
>>> list1;
[' daw ', 'lcd ', '11 56 ']

add to if Several examples of and other use examples

>>> list1 = [1, 2, 3];
>>> list2 = [4, 5, 6];
>>> [ x*x for x in list1 if x > 1]
[4, 9]
>>> [x*y for x in list1 for y in list2]
[4, 5, 6, 8, 10, 12, 12, 15, 18]
>>> [x+y for x in list1 for y in list2]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
>>> [list1[i]+list2[i] for i in range(len(list1))]
[5, 7, 9]
>>> [str(round(355/113, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

Nested list parsing

Convert the rows and columns as follows :

>>> myMat = [
... [1, 2, 3, 10],
... [4, 5, 6, 11],
... [7, 8, 9, 12]
... ]
>>>
>>> [ [ row[index] for row in myMat] for index in range(4)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [10, 11, 12]]
>>> listmat = []
>>> for i in range(4):
... listmat.append([row[i] for row in myMat])
...
>>> listmat
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [10, 11, 12]]
>>> listmat2 = []
>>> for item in range(4):
... temp_row = []
... for row in myMat:
... temp_row.append(row[item])
... listmat2.append(temp_row)
...
>>> listmat2
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [10, 11, 12]]

del Use

Used to delete a variable or an element in the list , But not with pop Return the deleted element
You can go directly through del a[index] That is, specify the elements of a specified index under a list

Tuples

Internal elements are used directly , Split it up , Generally, it will be put on after output () To distinguish

>>> tp1 = "dwjhd", 154, "zxcccc";
>>> tp1;
('dwjhd', 154, 'zxcccc')
>>> tp2 = tp1, "dwab", "mmn", 544;
>>> tp2;
(('dwjhd', 154, 'zxcccc'), 'dwab', 'mmn', 544)

Tuples can be nested

aggregate

The elements inside are out of order , No repetition . Use { } To create a collection , Can perform collection operations , And eliminate duplicate elements .
Use braces {} Create set . But if you want to create an empty set , Must use set() instead of {} ;{} Used to create an empty dictionary

Use { } After creating a collection, the elements in it will be automatically de duplicated , Some examples are as follows :

>>> a1 = {
"hahahaha", "dawdwd", "haha", 154, 145, 1, 2, 3, 4, 1, "dawdwd"}
>>> a1;
{
1, 2, 3, 4, 'dawdwd', 'hahahaha', 145, 'haha', 154}
>>> a2 = set('dajkciweifbkljbsfb')
>>> a2;
{
'k', 'c', 'f', 'j', 'l', 'i', 'a', 's', 'd', 'w', 'b', 'e'}
>>> a3 = set("mnbbvczx")
>>> a3;
{
'c', 'v', 'm', 'z', 'x', 'b', 'n'}
>>> a2 - a3; # Difference set 
{
'k', 'f', 'j', 'l', 'i', 'a', 's', 'd', 'w', 'e'}
>>> a2 & a3; # intersection 
{
'b', 'c'}
>>> a2 | a3; # Combine 
{
'c', 'f', 'm', 's', 'w', 'x', 'e', 'n', 'k', 'v', 'j', 'z', 'l', 'i', 'a', 'd', 'b'}
>>> a2 ^ a3; # Not in two sets at the same time 
{
'f', 'm', 's', 'w', 'x', 'e', 'n', 'k', 'v', 'j', 'z', 'l', 'i', 'a', 'd'}
>>> "haha" in a1;
True
>>> "haha" not in a1;
False

meanwhile Collections also support The derivation is similar to the list

>>> a = {
x for x in 'abcded' if x not in 'abc'}
>>> a
{
'd', 'e'}

Dictionaries

namely key value And Java Of Map

You can build a dictionary directly from the list of key value pair tuples :

>>> dict([('a', 1), ('b', 2), ('c', 3)])
{
'a': 1, 'b': 2, 'c': 3}

Dictionary derivation :

>>> {
x: x**2 for x in (2, 4, 6)}
{
2: 4, 4: 16, 6: 36}

If the keyword is just a simple string , It is sometimes more convenient to specify key value pairs with keyword parameters

>>> dict(a=1, b=2, c=3)
{
'a': 1, 'b': 2, 'c': 3}

Traverse the way :
1.key and The corresponding value can be used items() Read it out at the same time

>>> dict1 = {
"aa":124, "bb":125}
>>> for k,v in dict1.items():
... print(k, v)
...
aa 124
bb 125

2. When traversing in the sequence , Index location and corresponding value can be used enumerate() Also get

>>> for i, j in enumerate(['one', 'two', 'tri']):
... print(i, j)
...
0 one
1 two
2 tri

3. Traversing two or more sequences at the same time have access to zip()

>>> a1 = ['name', 'c', 'favorite color']
>>> b1 = ['xxx', 'cc', 'red']
>>> for q, a in zip(a1, b1):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is xxx.
What is your quest? It is cc.
What is your favorite color? It is red.

4, Traverse a sequence in reverse , First specify the sequence , And then call reversed() function

>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1

5. Traverse a sequence in order , Use sorted() Function returns a sorted sequence , The original value is not modified

>>> basket = ['apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear

Reference article python3 data structure


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved