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 = (':') 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'./') 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 = (3, portfolio, key=lambda s: s['price']) expensive = (3, portfolio, key=lambda s: s['price']) print(cheap) print(expensive)
3. Read streaming data source
If the data is from a continuous data source, we need to read the continuous data, next
We present a simple solution that applies to many really scenarios, however it is not universal.
Operational Steps:
In this section we want to show you how to read a live changing file and print out the input.
import time import os import sys if len() != 2: print('>>,"Please enter the name of the file to be read!"') filename = [1] if not (filename): print('>>,"Please give the required file:\%s\: is not a file" % filename') with open(filename,'r') as f: filesize = (filename)[6] (filesize) while True: where = () line = () if not line: (1) (where) else: print(line)
This Python read real-time data streaming example above is all that I have shared with you.