python List - Tuple - Set - Dict - Array - Namedtuple

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python List - Tuple - Set - Dict - Array - Namedtuple相关的知识,希望对你有一定的参考价值。

# CREATION
tuple  |  ()   |  (  'edu', )  |  (  'edu',   'lety',   'karen' )  # inmutable
list   |  []   |  [  'edu'  ]  |  [  'edu',   'lety',   'karen' ]  # mutable
set    |  set  |  {  'edu'  }  |  {  'edu',   'lety',   'karen' }  # mutable
dict   |  {}   |  {1:'edu'  )  |  {1:'edu', 2:'lety', 3:'karen' }  # mutable

#GENERATOR EXPRESION
tuple  |  (x     for x in range(10) if i % 2 == 0 )  |  list(tuple)

# COMPRESION
list   |  [x     for x in range(10) if i % 2 == 0 ]
set    |  {x     for x in range(10) if i % 2 == 0 }
dict   |  {x:x*x for x in range(10) if i % 2 == 0 }

# CLONE
tuple  |  tuple[:]
list   |  list(original_list) 
set    |  set(original_set)
dict   |  dict(original_dict)

# SORT
dict   |  dict.sort()  |  sorted(dict.items(), key=lambda x: x[1], reverse=True)

# MERGE
dict   |  zs.update(ys)...  |  zs = dict(xs, **ys)  |  zs = {**xs, **ys} (python > 3.5)

# FUNCTIONS
tuple  |  .index .count
list   |  .index .count .append .extend .insert .remove .pop .sort .reverse
set    |  .intersection .issubset .issuperset .difference .symetric_difference .copy
dict   |  .get .keys .values .itemps .has_key .pop .popitem .copy .clear .fromkeys .update

# STACKS  
from queue       import LifoQueue
from collections import deque
list       |  stack = []           |  stack.append(x)  |  stack.pop()
deque      |  stack = deque()      |  stack.append(x)  |  stack.pop()
LifoQueue  |  stack = LifoQueue()  |  stack.put(x)     |  stack.get()      |  stack.get_nowait()

# QUEUES
from queue import Queue
list       |  queue = []           |  queue.append(x)  |  queue.pop(0)
deque      |  queue = deque()      |  queue.append(x)  |  queue.popleft()
Queue      |  queue = Queue()      |  queue.put(x)     |  queue.get()      |  queue.get_nowait()

# PRIORITY QUEUES
import heapq
from queue import PriorityQueue
list           |  q = []  |  q.append((2, 'code'))  |  q.sort(reverse=True)  |  while q: q.pop()
heapq          |  q = []  |  heapq.heappush(q, (2, 'code'))                  |  while q: heapq.heappop(q)
PriorityQueue  |  q = PriorityQueue()  |  q.put((2, 'code'))                 |  while not q.empty(): q.get()

# PRINT
>>> import json
>>> json.dumps(mapping, indent=4, sort_keys=True)
{
  "a": 23,
  "b": 42,
  "c": 12648430
}

>>> import pprint
>>> pprint.pprint(mapping)
{'a': 23, 'b': 42, 'c': 12648430, 'd': set([1, 2, 3])}
# ARRAYs
import array
arr = array.array('f', (1.0, 1.5, 2.0, 2.5))

# BYTEARRAY
arr = bytes((0, 1, 2, 3))

# NAMEDTUPLES
from collections import namedtuple
Point = namedtuple('Point', 'x y z')(1, 2, 3)
Car = namedtuple('Car' , 'color mileage')
Car = namedtuple('Car', ['color', 'mileage'])
ElectricCar = namedtuple('ElectricCar', Car._fields + ('charge',))
my_car_1 = Car('red', 3812.4)
my_car_2 = ElectricCar('red', 1234, 45.0)
>>> json.dumps(my_car._asdict())
'{"color": "red", "mileage": 3812.4}'

# STRUCT
from struct import Struct
MyStruct = Struct('i?f')
data = MyStruct.pack(23, False, 42.0)
# All you get is a blob of data:
>>> data
b'\x17\x00\x00\x00\x00\x00\x00\x00\x00\x00(B'
# Data blobs can be unpacked again:
>>> MyStruct.unpack(data)
(23, False, 42.0)

# SIMPLENAMESPACE
from types import SimpleNamespace
car1 = SimpleNamespace(color='red', mileage=3812.4, automatic=True)
# The default repr:
>>> car1
namespace(automatic=True, color='red', mileage=3812.4)
# Instances support attribute access and are mutable:
>>> car1.mileage = 12
>>> car1.windshield = 'broken'
>>> del car1.automatic
>>> car1
namespace(color='red', mileage=12, windshield='broken')

以上是关于python List - Tuple - Set - Dict - Array - Namedtuple的主要内容,如果未能解决你的问题,请参考以下文章

Python中的list与tuple集合

Python list和tuple的相互转换?

Python里面如何实现tuple和list的转换

Python中list,tuple,dict,set的区别和用法

Python列表(list)、元祖(tuple)、集合(set),和字典(dictionary)区别和联系

python 元组操作(tuple)