是否有可能使用相同的地圖reduce在python中轉換此js代碼?JS到python lambda/list comp轉換
var fs = require('fs')
var output = fs.readFileSync('data.txt', 'utf8')
.trim()
.split('\n')
.map(line => line.split('\t'))
.reduce((orders, line) => {
orders[line[0]] = orders[line[0]] || []
orders[line[0]].push({
name: line[1],
price: line[2],
quantity: line[3]
})
return orders
}, {})
console.log(output)
到目前爲止,我只有到代碼的地圖部分:
txt = open('data.txt').read()
mylist = map(lambda x: x.split('\t'), txt.strip().split('\n'))
不知道這是可能做到這一點在lambda /列表比較。任何方式都可以。多謝你們!
----更新1 ---- 感謝@Univerio的答案
附加學習。你們是否有什麼這個問題被拋出NoneType爲{}
with open("data.txt") as txt:
output = reduce(lambda x,y : x.setdefault(y[0], []).append({"name": y[1], "price": y[2], "quantity": y[3]}).items(),\
map(lambda x: x.split('\t'), txt.read().strip().split('\n')),\
{})
print output
任何想法----更新2 ----
那麼它是醜陋的。但得到它與相同的地圖縮小工作。
def update_orders(orders, line):
orders.setdefault(line[0], []).append({"name": line[1], "price": line[2], "quantity": line[3]})
#orders[line[0]] = orders.get(line[0], []) + [{"name": line[1], "price": line[2], "quantity": line[3]}]
return orders
with open("data.txt") as txt:
output = reduce(lambda x,y : update_orders(x, y),\
map(lambda x: x.split('\t'), txt.read().strip().split('\n')),\
{})
print output
如果您描述了代碼的作用以及您期望的輸入/輸出,這將會很有幫助。無論如何,一個好的python解決方案不會模仿你的原始代碼行。 – timgeb
@timgeb,它是一個帶有4列的製表符分隔文件 – codeffreak