您好,登錄后才能下訂單哦!
1、#coding:utf-8
chose = [ ('foo',1,2), ('bar','hello'), ('foo',3,4) ] def do_foo(x,y): print('foo',x,y) def do_bar(s): print('bar',s) for tag,*args in chose: if tag == 'foo': do_foo(*args) elif tag == 'bar': do_bar(*args) line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false' uname,*fields,homedir,sh = line.split(':') print(sh) from collections import deque def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for li in lines: if pattern in li: yield li, previous_lines previous_lines.append(li) # Example use on a file if __name__ == '__main__': with open(r'./somefiles.py') as f: for line, prevlines in search(f, 'python', 5): for pline in prevlines: print(pline, end='') print(line, end='') print('-' * 20)
2、import heapq
portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) print(cheap) print(expensive)
3、讀取流數(shù)據(jù)源
如果數(shù)據(jù)是來自一個(gè)連續(xù)的數(shù)據(jù)源,我們需要讀取連續(xù)數(shù)據(jù),接下來
我們介紹一個(gè)適用于許多真是場(chǎng)景的簡(jiǎn)單解決方案,然而它并不是通用的。
操作步驟:
在本節(jié)中我們將想你演示如何讀取一個(gè)實(shí)時(shí)變化的文件,并把輸入打印出來。
import time import os import sys if len(sys.argv) != 2: print('>>sys.stderr,"請(qǐng)輸入需要讀取的文件名!"') filename = sys.argv[1] if not os.path.isfile(filename): print('>>sys.stderr,"請(qǐng)給出需要的文件:\%s\: is not a file" % filename') with open(filename,'r') as f: filesize = os.stat(filename)[6] f.seek(filesize) while True: where = f.tell() line = f.readline() if not line: time.sleep(1) f.seek(where) else: print(line)
以上這篇Python讀取實(shí)時(shí)數(shù)據(jù)流示例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。