Scribbling

Python Data Structures: Sequences 본문

Computer Science/Python

Python Data Structures: Sequences

focalpoint 2022. 3. 21. 12:42

 

1. List / Generator Comprehension

Using list / generator comprehension makes code more readable while enhancing efficiency.

suits = ['Spades', 'Diamonds', 'Hearts', 'Clubs']
ranks = [str(i) for i in range(2, 11)] + list('JQKA')

for card in (f"{suit} {rank}" for suit in suits for rank in ranks):
    print(card)

 

2. Tuple Unpacking

a, b, *rest = range(1, 5)
print(a, b, rest)

 

3. NamedTuple

Namedtuple is very useful to use tuples as records.

from collections import namedtuple

Person = namedtuple('Person', 'name age')

p1 = Person('Morgan', 27)
print(p1.name)
print(p1[-1])

from collections import namedtuple

Person = namedtuple('Person', 'name age')

print(Person._fields)

info = ('JY', 27)
p2 = Person._make(info)

for k, v in p2._asdict().items():
    print(k, v)

 

 

4. Slice object

In python, a:b:c denotes a slice(a, b, c) object. 

invoice = '''
No...Price...Quantity...
01   $7.50   3 
02   $8.49   4
03   $1.22   1000
'''

NO = slice(0, 5)
Price = slice(5, 13)
Quantity = slice(13, 20)

line_items = invoice.split('\n')[2:]
for item in line_items:
    print(item[NO], item[Price], item[Quantity])

 

5. Byte object

There are 3 ways to create an byte object as below.

print(bytes(10))

print(bytes([10, 20, 30]))

print(b'hello world')
x = 'hello word'.encode()
print(x)
print(x.decode('utf-8'))

 

 

'Computer Science > Python' 카테고리의 다른 글

Python: Memoryview function  (0) 2022.03.23
Python Immutable Dictionary, Set  (0) 2022.03.22
Python Magic Methods: Pythonic Data Model  (0) 2022.03.16
Python Grammar: Things that I forget often  (0) 2022.03.14
Python String Methods  (0) 2022.01.18