python對流進行join

2021-06-27 04:07:15 字數 2364 閱讀 6757

對流的合併,有時各個流的進度需要根據資料的不同而定。

def joinstreams(instreams,getnext=lambda data,livings:livings):

'''把各流進行關聯,instreams是流陣列,

getnext函式決定從哪些流中取下一批資料,輸入引數為流編號,輸出應為需要從哪些流編號讀資料的陣列'''

data = [ () for s in instreams ]

livings = list(range(len(instreams)))

while true:

got =

while not got:

if not livings:

raise stopiteration

togets = getnext(data,livings)

for toget in togets:

try:

data[toget] = instreams[toget].next()

except:

livings.remove(toget)

yield data,got

#測試資料

cat data.txt

a       1

b       3

c       5

d       7

cat data2.txt

x       2

y       4

z       6

#對兩個流按值排序,相當於合併兩個排序檔案的歸併排序

stream1 = imap(lambda x:x.strip().split(),open("data.txt"))

stream2 = imap(lambda x:x.strip().split(),open("data2.txt"))

def sortfunc(data,livings):

existdata = [(data[ii][1] if data[ii] else none,ii) for ii in livings]

return [sorted(existdata)[0][1]]

ss = joinstreams([stream1,stream2],sortfunc)

from itertools import starmap

from functools import reduce

r=starmap(lambda x,ii:reduce(list.__add__,[x[i] for i in ii]),ss)

for l in r:

print("\t".join(l))

a       1

x       2

b       3

y       4

c       5

z       6

d       7

#逐個流取值,相當於兩個檔案合併

stream1 = imap(lambda x:x.strip().split(),open("data.txt"))

stream2 = imap(lambda x:x.strip().split(),open("data2.txt"))

ss=joinstreams([stream1,stream2],lambda d,x:[x[0]])    #僅此句不同

r=starmap(lambda x,ii:reduce(list.__add__,[x[i] for i in ii]),ss)

for l in r:

print("\t".join(l))

a       1

b       3

c       5

d       7

x       2

y       4

z       6

#把兩個流做join,相當於paste

stream1 = imap(lambda x:x.strip().split(),open("data.txt"))

stream2 = imap(lambda x:x.strip().split(),open("data2.txt"))

ss=joinstreams([stream1,stream2])

r=starmap(lambda x,ii:reduce(list.__add__,[x[i] for i in ii]),ss)

for l in r:

print("\t".join(l))

a       1       x       2

b       3       y       4

c       5       z       6

d       7

C 使用流進行輸入輸出

首先應用 include include1.進製讀寫 int val 10 十進位制數 cout 輸出8進製 輸出16進製制 輸出10進製 2.精度 double pi 3.141592658 cout 4 設定小數精確度,影響以下所有輸出 cout cout cout e 0003.對齊文字和設定...

C 使用流進行輸入輸出

首先應用 include include1.進製讀寫 int val 10 十進位制數 cout 輸出8進製 輸出16進製制 輸出10進製 2.精度 double pi 3.141592658 cout 4 設定小數精確度,影響以下所有輸出 cout cout cout e 0003.對齊文字和設定...

C 語法之使用流進行輸入輸出

流取出運算子 cout setiosflags ios base hex ios base showbase ios base uppercase cout 使用std fstream處理檔案 使用open和close開啟和關閉檔案,open引數為打卡路徑和檔案開啟模式 開啟模式可選 分別使用 和 ...