美文网首页
Python基础类型

Python基础类型

作者: 多问Why | 来源:发表于2019-03-25 18:03 被阅读0次
  1. unpack列表到变量中
x,y = p
assert x == 'a' and y == 2
p = ['a',2]
x,y = p
assert x == 'a' and y == 2

不只是tuple和list,任意iterable的数据结构都可以。

  1. 处理任意长度的列表
assert middle == ['b','c']
assert last == 'd'
first,*middle,last = ['a','d']
assert middle == []
assert last == 'd'

这样先匹配单个的变量,剩下的进入*变量。

  1. 定长队列
from collections import deque

q = deque(maxlen=2)
q.append('a')
q.append('b')
q.append('3')
assert list(q) == ['b','3']
q.popleft() == 'b'
#它可以从左右两方追加和弹出

4.找出最大最小的N个元素

import heapq

nums = range(10, 100)
assert heapq.nlargest(5,nums) == [99, 98, 97, 96, 95]
assert heapq.nsmallest(5,nums) == list(range(10,15))

employees = [{'name': 'Tom','age': 20},
             {'name': 'Lily', 'age': 29},
             {'name': 'Lucy', 'age': 23},
             {'name': 'Jack', 'age': 25}]

assert heapq.nsmallest(2, employees, key=lambda x: x['age']) == [employees[0], employees[2]]

nums = [3, 1, -4, 5]
# make the first one is the smallest item
heapq.heapify(nums)
nums == [-4, 3, 1, 5]
assert -4 == heapq.heappop(nums)
# heappop is pop + heapify
[1, 3, 5] == nums
  1. Tuple的比较
assert (1, TypeError()) < (2, IOError())
assert (1, 3, -9) > (1, 2, 10)
import unittest

class TestSum(unittest.TestCase):

    def test_type_error(self):
        with self.assertRaises(TypeError):
            (1,IOError()) < (1,TypeError())

unittest.main()

从第一个元素开始比较,一旦能确定大小,就停止比较。
如果遇到不能比较的元素,则报错。

  1. dict的值是列表时
from collections import defaultdict

# group people by class and store into a dict
data = """class1,Tom
class1,Lily
class2,Jack
class3,John"""

# traditional method
d = {}

for row in data.splitlines():
    c, name = row.split(',')
    if c not in d:
        d[c] = []
    d[c].append(name)
assert {'class1': ['Tom', 'Lily'], 'class2': ['Jack'], 'class3': ['John']} == d

# use defaultdict
d = defaultdict(list)

for row in data.splitlines():
    c, name = row.split(',')
    d[c].append(name)
print(d)

defaultdict(set)时,相当于key对应的值为set().

  1. dict排序,最大值,返回key和value
d = {'foo': 45.23,
'bar': 612.78,
'spam': 205.55}
ele_sorted = sorted(zip(d.values(), d.keys()))
print(ele_sorted)
max_price = max(zip(d.values(), d.keys()))
print(max_price)

zip返回一个列表,每个元素是个tuple.

  1. Finding Commonalities in Two Dictionaries
d = {'foo': 45,
     'bar': 612.78,
     'spam': 205.55}
b = {
    'x': 10,
    'bar': 30,
    'foo': 45
}
common_key = d.keys() & b.keys()
common_key == {'foo', 'bar'}
d.keys() - b.keys() == {'spam'}
d.items() & b.items() == {('foo', 45)}

主要是dict的keys()和items()返回值都支持unions, intersections and differences这些set()的操作。
9.Naming a slice

message = 'TOM__JAN141990MaleY'
gender = slice(14, 18)
assert message[14:18] == message[gender]

命名一个slice能够让人容易明白变量的用途。

10.统计列表中元素个数

from collections import Counter

words = "There is no royal road to mathematics."
word_counts = Counter(words)
top_three = word_counts.most_common(3)
assert [(' ', 6), ('o', 4), ('a', 4)] == top_three
assert word_counts['T'] == 1

word_counts.update('That')
assert word_counts['T'] == 2

# counter can add or sub
a = Counter('That')
b = Counter('This')
ab = a-b
assert ab['T'] == 0
  1. 根据对象属性排序
from operator import itemgetter
rows = [
    {'name': 'Jones', 'id': 1003},
    {'name': 'Tom', 'id': 1002},
    {'name': 'Jones', 'id': 1004}
]

assert sorted(rows, key=itemgetter('id')) == sorted(rows, key=lambda x: x['id'])
assert max(rows, key=itemgetter('id', 'name')) == {'name': 'Jones', 'id': 1004}

itemgetter()的运行效率更高些。

相关文章

网友评论

      本文标题:Python基础类型

      本文链接:https://www.haomeiwen.com/subject/xmvbvqtx.html