是否可以使用相同的map reduce在python中转换这个js代码?你知道吗
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/list comp中执行此操作。任何方法都可以。谢谢你们!你知道吗
----更新1---- 谢谢@Univerio的回答
额外学习。你们知道把它作为{}的非类型抛出有什么问题吗
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中,使用循环而不是
reduce
更为惯用。您还可以通过以下方式利用流式文件访问:这与JS版本在空白处理方面所做的不完全相同,但是对于正常的输入来说应该可以。你知道吗
相关问题 更多 >
编程相关推荐