Python Data structure

Source: Internet
Author: User

1 List methods
list.append(x) # 添加一个元素xlist.extend(L) # 添加L列表中的所有元素list.insert(i,x) # 在列表指定位置插入一个元素list.remove(x) # 删除列表中值为x的元素list.pop(i) # 删除列表中指定位置的元素并返回元素值list.clear() # 清空列表list.index(x) # 返回列表中第一个值为x的元素索引list.count(x) # 返回列表中x出现的次数list.sort() # 对列表进行排序list.reverse() # 返回列表元素的逆序排列list.copy() # 浅拷贝
1.1 List as a stack

Use append () to add elements, pop () to take out elements.

stack = [3, 4, 5]stack.apppend(6)stack.pop()
1.2 List as queue
from collections import dequequeue = deque(["Eric", "John", "Michael"])queue.append("Terry")queque.popleft()
1.3 List-derived
# 普通方法squares = []for x in range(10):    squares.append(x**2)# 列表推导式squares = list(map(lambda x: x**2, range(10)))squares = [x**2 for x in range(10)]

Some examples:

>>> VEC = [ -4,-2, 0, 2, 4]>>> # Create a new list with the values doubled>>> [x*2 to X in VEC ][-8, -4, 0, 4, 8]>>> # Filter the list to exclude negative numbers>>> [x for x in VEC if x >= 0][0, 2, 4]>>> # Apply a function to all the elements>>> [ABS (x) for x in Vec][4, 2, 0, 2, 4]>>> # CA ll a method on each element>>> freshfruit = [' banana ', ' loganberry ', ' passion fruit ']>>> [weapon. Strip () for weapon in freshfruit][' banana ', ' loganberry ', ' passion fruit ']>>> # Create a list of 2-tuples like (n umber, Square) >>> [(x, X**2) for X in range (6) [(0, 0), (1, 1), (2, 4), (3, 9), (4,), (5),]>>> # t He tuple must be parenthesized, otherwise a error is raised>>> [x, x**2 for x in range (6)] File "<stdin>"    , line 1, in? [x, x**2 for x in range (6)] ^syntaxerror:invalid syntax>>> # Flatten a list using a listcomp with Both ' For ' >>> VEC = [[[7,8,9]]>>>], [4,5,6], [num for elem in VEC for num in Elem][1, 2, 3, 4, 5, 6, 7, 8 , 9]

List expressions also support more complex expressions and nested functions:

from math import pi[str(round(pi, i)) for i in range(1, 6)]
1.4 Nested list expressions
matrix = [    [1, 2, 3, 4],    [5, 6, 7, 8],    [9, 10, 11, 12],]# 交换行与列[[row[i] for row in matrix] for i in range(4)]# s使用zip()函数list(zip(*matrix))
2 del statement

Delete the specified value by index

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>> del a[2:4]>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[]

Del can also delete the entire variable:

>>> del a
3-Tuple and sequence 4-collection
>>> basket = {' Apple ', ' orange ', ' apple ', ' pear ', ' orange ', ' banana '}>>> print (basket)                 # show that duplicates has been removed{' orange ', ' banana ', ' pear ', ' apple '}>>> ' orange ' in basket # Fast Membership testingtrue>>> ' Crabgrass ' in basketfalse>>> # demonstrate set operations on UN                                  Ique Letters from Words...>>> a = set (' Abracadabra ') >>> B = Set (' Alacazam ') >>> a # Unique letters in a{' a ', ' R ', ' B ', ' C ', ' d '}>>> A-B # let Ters in A and not in b{' R ', ' d ', ' B '}>>> a |                              B # Letters in either A or b{' a ', ' C ', ' R ', ' d ', ' B ', ' m ', ' Z ', ' l '}>>> A & B  # Letters in both A and b{' a ', ' C '}>>> a ^ B # letters in A or B but not both{' R ', ' d ', ' B ', ' m ', ' Z ', ' l '}# set derivation >>> a = {x for x in ' AbracAdabra ' If x not in ' abc '}>>> a{' R ', ' d '} 
5 Dictionaries
>>> tel = {‘jack‘: 4098, ‘sape‘: 4139}>>> tel[‘guido‘] = 4127>>> tel{‘sape‘: 4139, ‘guido‘: 4127, ‘jack‘: 4098}>>> tel[‘jack‘]4098>>> del tel[‘sape‘]>>> tel[‘irv‘] = 4127>>> tel{‘guido‘: 4127, ‘irv‘: 4127, ‘jack‘: 4098}>>> list(tel.keys())[‘irv‘, ‘guido‘, ‘jack‘]>>> sorted(tel.keys())[‘guido‘, ‘irv‘, ‘jack‘]>>> ‘guido‘ in telTrue>>> ‘jack‘ not in telFalse

Use Dict () to construct a dictionary

dict(sape=4139, guido=4127, jack=4908)dict([(‘sape‘, 4139), (‘guido‘, 4127), (‘jack‘, 4098)])

Create a dictionary with an almost expression

{x: x**2 for x in (2, 4, 6)}
6 Cycle Tips

The traversal of keywords and values in a dictionary can be used in items() methods

knights = {‘gallahad‘: ‘the pure‘, ‘robin‘: ‘the brave‘}for k, v in knights.items():    print(k,v)

The traversal of indexes and corresponding values in a sequence can be enumerate()

for i, v in enumerate([‘tic‘, ‘tac‘, ‘toe‘]):    print(i, v)

When traversing multiple sequences at the same time, you can use the zip() method

questions = [‘name‘, ‘quest‘, ‘favorite color‘]answers = [‘lancelot‘, ‘the holy grail‘, ‘blue‘]for q, a in zip(questions, answers):    print(‘What is your {0}? It is {1}.‘.format(q, a))

Reverse-order traversal, using reversed() methods

for i reversed(range(1, 10, 2)):    print(i)
7 in-depth condition control
>>> string1, string2, string3 = ‘‘, ‘Trondheim‘, ‘Hammer Dance‘>>> non_null = string1 or string2 or string3
8 comparing sequences and other types

Sequence objects can be compared with the same type.

(1, 2, 3)              < (1, 2, 4)[1, 2, 3]              < [1, 2, 4]‘ABC‘ < ‘C‘ < ‘Pascal‘ < ‘Python‘(1, 2, 3, 4)           < (1, 2, 4)(1, 2)                 < (1, 2, -1)(1, 2, 3)             == (1.0, 2.0, 3.0)(1, 2, (‘aa‘, ‘ab‘))   < (1, 2, (‘abc‘, ‘a‘), 4)

Python Data structure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.