Wenwen Lin

Wenwen Lin的博客

他的个人主页  他的博客

list学习中的问题(二)

Wenwen Lin  2012年11月30日 星期五 11:29 | 1023次浏览 | 0条评论

调试程序,并解决python中list数据结构的sort方法的使用中出现的一个问题。问题的描述是“ValueError: 3 is not in list”

第一段代码

# -*- coding: utf-8 -*-
"""
Created on Wed Nov 28 18:26:34 2012

@author: Administrator
"""
sister = range(1, 6)
gMom = sister[:]
brother = range(5, 0, -1)
gDad = brother[:]
job_size = 5
cut = 1
index_snippet = [brother.index(elem) for elem in sister[cut:job_size]]
genome_snippet = sister[cut:job_size]
#genome_snippet_copy = genome_snippet[:]
#genome_snippet.sort(cmp=lambda x,y : cmp(index_snippet[genome_snippet.index(x)], index_snippet[genome_snippet.index(y)]))
#genome_cmp =  lambda x,y : cmp(index_snippet[genome_snippet_copy.index(x)], index_snippet[genome_snippet_copy.index(y)])
genome_cmp =  lambda x,y : cmp(index_snippet[genome_snippet.index(x)], index_snippet[genome_snippet.index(y)])
genome_snippet.sort(cmp=genome_cmp)
print genome_snippet

 

运行程序,出现以下问题

Traceback (most recent call last):
  File "E:\Python Project\simple.py", line 19, in <module>
    genome_snippet.sort(cmp=genome_cmp)
  File "E:\Python Project\simple.py", line 18, in <lambda>
    genome_cmp =  lambda x,y : cmp(index_snippet[genome_snippet.index(x)], index_snippet[genome_snippet.index(y)])
ValueError: 3 is not in list

调试程序发现, genome_snippet在sort方法变成了空list,所以找不到value 为3的元素

第二段代码

# -*- coding: utf-8 -*-
"""
Created on Wed Nov 28 18:26:34 2012

@author: Administrator
"""
sister = range(1, 6)
gMom = sister[:]
brother = range(5, 0, -1)
gDad = brother[:]
job_size = 5
cut = 1
index_snippet = [brother.index(elem) for elem in sister[cut:job_size]]
genome_snippet = sister[cut:job_size]
genome_snippet_copy = genome_snippet[:]
#genome_snippet.sort(cmp=lambda x,y : cmp(index_snippet[genome_snippet.index(x)], index_snippet[genome_snippet.index(y)]))
genome_cmp =  lambda x,y : cmp(index_snippet[genome_snippet_copy.index(x)], index_snippet[genome_snippet_copy.index(y)])
#genome_cmp =  lambda x,y : cmp(index_snippet[genome_snippet.index(x)], index_snippet[genome_snippet.index(y)])
genome_snippet.sort(cmp=genome_cmp)
print genome_snippet

将genome_snippet的值先保存到genome_snippet_copy中,在lambda语句中用genome_snippet_copy代替genome_snippet后,问题解决,运行结果也是正确的

 

评论

我的评论:

发表评论

请 登录 后发表评论。还没有在Zeuux哲思注册吗?现在 注册 !

暂时没有评论

Zeuux © 2024

京ICP备05028076号