python 3-4如何进行反向迭代以及如何实现反向迭代

利用生成器做了一个浮点的步进器,reversed()调用的是内部的reversed方法

 class FloatRange:
    def __init__(self, start, end, step=0.1):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        value = self.start
        while value <= self.end:
            yield value
            value += self.step

    def __reversed__(self):
        value = self.end
        while value >= self.start:
            yield value
            value -= self.step

print("顺序:")

for x in FloatRange(1.0, 4.0, 0.5):
    print(x)

print("\n倒序:")

for x in reversed(FloatRange(1.0, 4.0, 0.5)):
    print(x)

python 3-3如何使用生成器函数实现可迭代对象

重点是yield的使用,传说中的生成器,主要看yield后面的值,就是遍历输出的值

class PrimeNum:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def isPrime(self, k):
        if k < 2:
            return False
        for x in range(2, k):
            if k % x == 0:
                return False
        return True

    def __iter__(self):
        for x in range(self.start, self.end + 1):
            if self.isPrime(x):
                yield x

for x in PrimeNum(1, 100):
    print(x)

python 3-2如何实现可迭代对象和迭代器对象(2)

实现可迭代对象和迭代器对象。

  1. 先定义一个Iterator实现next
  2. 再定义一个weatherIterable实现iter
  3. 最后使用for in 遍历解决
import requests
from collections.abc import Iterable, Iterator


class weatherIterator(Iterator):
    index = 0

    def __init__(self, cities):
        self.cities = cities

    def __next__(self):
        if self.index == len(self.cities):
            raise StopIteration
        city = self.cities[self.index]
        self.index = self.index + 1
        return self.getweather(city)

    #获取天气接口API
    def getweather(self, s):
        cities = {'北京': 'CH010100', '上海': 'CH020100', '广州': 'CH280101'}
        # 北京:CH010100 上海:CH020100 广州:CH280101
        # CH280101 http://api.yytianqi.com/forecast7d?city=CH280101&key=rsdo40081gvhnecf
        r = requests.get("http://api.yytianqi.com/forecast7d?city=%s&key=rsdo40081gvhnecf" % cities[s])
        data = r.json()['data']['list'][0]
        return "%s: 白天气温 %s ℃, 夜间气温 %s ℃" % (s, data['qw1'], data['qw2'])


class weatherIterable(Iterable):
    def __init__(self, cities):
        self.cities = cities

    def __iter__(self):
        return weatherIterator(self.cities)


# 先定义一个Iterator实现__next__,再定义一个weatherIterable实现__iter__,最后使用for in 遍历解决
cities = ['北京', '上海', '广州']
for x in weatherIterable(cities):
    print(x)

python 2-7如何实现用户的历史记录功能(最多n条)

猜数字的游戏,利用pickle存储历史数据,利用raw_input获取输入数据,利用deque双向队列实现数据的排队

from random import randint
from collections import deque
from code import InteractiveConsole
import pickle

N = randint(0, 100)
history = deque([], 5)


def guess(k):
    if k == N:
        print("you are right")
        return True
    elif k > N:
        print("num is lower than %s" % k)
    elif k < N:
        print("num is greater than %s" % k)
    return False


while (True):

    try:
        history = pickle.load(open("./history.txt", "rb"))
    except:
        pass

    line = InteractiveConsole.raw_input("please input a num")
    if line.isdigit():
        kk = int(line)
        history.append(line)
        pickle.dump(history, open("./history.txt", "wb"))
        if guess(kk):
            break
        else:
            continue
    elif line == 'history' or line == 'h?':
        print(list(history))
    elif line == 'quit' or line == 'exit' or line == "q?":
        break

python 2-6如何让字典保持有序

字典是无序的

dict = {}
dict['a'] = (1, 34)
dict['b'] = (3, 22)
dict['c'] = (2, 39)
for x in dict: print(x)

有序的字典

from collections import OrderedDict
dict = OrderedDict()
dict['a'] = (1, 34)
dict['b'] = (3, 22)
dict['c'] = (2, 39)
for x in dict: print(x)

模拟选手做题,最后保存选手排名和做题时间

from time import time
from random import randint
from collections import OrderedDict
from code import InteractiveConsole

d = OrderedDict()
players = list('ABCDEFGHIJ')
start = time()

for i in range(0, 10):
    InteractiveConsole.raw_input("")
    p = players.pop(randint(0, 9 - i))
    end = time()
    d[p] = (i + 1, end - start)
    print(i + 1, p, end - start)

print('-' * 20)

for x in d:
    print(x, d[x])

python 2-5如何快速找到多个字典中的公共键(key)

from random import randint, sample
sample('abcxyz', 4)
sample('abcxyz', randint(3, 5)

得到初始序列

s1 = {x: randint(1,4) for x in sample('abcxyz', randint(4,6))}
s2 = {x: randint(1,4) for x in sample('abcxyz', randint(4,6))}
s3 = {x: randint(1,4) for x in sample('abcxyz', randint(4,6))}

第一种方法

for k in s1:
...     if k in s2 and k in s3:
...             res.append(k)

第二种方法

s1.keys()
s1.keys() & s2.keys() & s3.keys()

第三种方法

map(dict.keys, [s1, s2, s3])
from functools import reduce
reduce(lambda a, b : a & b, map(dict.keys, [s1, s2, s3]))

python 2-3如何统计序列中元素的出现频度

from random import randint
data = [randint(1, 10) for _ in range(20)]
d = dict.fromkeys(data, 0)
d
for x in data:
… d[x] += 1
d

from collections import Counter
c = Counter(data)
c.most_common()
c.most_common(1)
c.most_common(2)
file = open(“/Users/dukelight/project/EasyPR/LICENSE”, “r”).read()
words = re.split(“\W+”, file)
wordsCounter = Counter(words)
wordsCounter.most_common(10)