请有人可以帮助我了解为什么该程序的输出是:
def group_by_owners(files):
dt = {}
for i,j in files.items():
if j in dt.keys():
dt[j] = dt[j].append(i) # Re-assigning the element. This is where the issue is present.
else:
dt[j]=[i]
return dt
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
print(group_by_owners(files))
而不是预期的输出:
Stopped at: NaN
谢谢
这段代码是用JS ES6编写的
Stopped at: 3
答案 0 :(得分:1)
存在参考问题,已更正代码。
function StopWatch(){
var me = this;
this.watchtime = 0;
this.started = 0;
this.start = function(){
if(this.started){
d = new Date()
console.log("Cannot start watch twice. Current time is", (d.getTime() - this.watchtime)/1000)
}else if(this.watchtime == 0){
this.started = 1
d = new Date()
this.watchtime = d.getTime()
}
else{
d = new Date()
console.log("Stopwatch re-started from", (d.getTime() - this.watchtime)/1000)
this.watchtime = d.getTime() - this.watchtime
this.started = 1
}
}
this.stop = function(){
if (this.started == 0){
console.log("Stopwatch has not yet been started")
}else{
d = new Date()
this.total_time = (d.getTime() - me.watchtime)/1000
console.log("Stopped at:", this.total_time)
this.started = 0
}
}
}
sw = new StopWatch;
sw.start();
setTimeout(sw.stop, 3000);
创建变量me
,并用this
对其进行初始化,然后在stop
函数中,将this.watchtime
替换为me.watchtime
答案 1 :(得分:1)
使用ES6时,使用Arrow函数将解决参考问题。
function StopWatch() {
this.watchtime = 0;
this.started = 0;
this.start = () => {
if (this.started) {
d = new Date()
console.log("Cannot start watch twice. Current time is", (d.getTime() - this.watchtime) / 1000)
} else if (this.watchtime == 0) {
this.started = 1
d = new Date()
this.watchtime = d.getTime()
} else {
d = new Date()
console.log("Stopwatch re-started from", (d.getTime() - this.watchtime) / 1000)
this.watchtime = d.getTime() - this.watchtime
this.started = 1
}
}
this.stop = () => {
if (this.started == 0) {
console.log("Stopwatch has not yet been started")
} else {
d = new Date()
this.total_time = (d.getTime() - this.watchtime) / 1000
console.log("Stopped at:", this.total_time)
this.started = 0
}
}
}
sw = new StopWatch
sw.start()
setTimeout(sw.stop, 3000)
如果您不了解Arrow函数,请阅读here。