今天继续讲述列表(list)的常用方法。 共有index()、count()、reverse()、sort()、copy()五种方法。 1。index() index(X)。返回列表中第一为X的索引值,没有则抛出异常; 2。count() count(X)。返回列表X的个数,没有则返回0; 3。reverse() reverse()。用于翻转列表中的元素。 4。sort() sort()。用于对列表中的元素进行排序,可指定排序的规则,其默认规则为从小到大。 5。copy() copy()。有浅复制和深复制之分,对于浅复制后的list1,对list1中可变数据进行改变也会改变原来的列表中的可变数据;深复制deepcopy()则可避免这种情况;若有两个变量指向同一个列表,改变任一列表数据,另一个也会改变。 推导式 简单来说,以相对简单的语句实现较为复杂的功能。 简单的例子,对1到10的数字进行平方并添加到列表中。运用推导式可以一句语句实现。 其他功能下篇详细了解。 英文翻译 TodayIwillcontinuetotalkaboutthecommonmethodsoflists。 Therearefivemethods:index(),count(),reverse(),sort()andcopy()。 1。Index(X)。ReturnthefirstindexvalueofXinthelist,ifnot, 2。Count(X)。ReturnthenumberoflistX,ifnot,return0; 3。reverse()。Usedtofliptheelementsinthelist。 4。sort()。Usedtosorttheelementsinthelist,youcanspecifythesortingrules,andthedefaultruleisfromsmalltolarge。 5。Copy()。Thereareshallowcopyanddeepcopy。Forlist1aftershallowcopy,changingthevariabledatainlist1deepcopydeepcopy()ifthereisTwovariablespointtothesamelist,andifyouchangeanylistdata,theotherwillalsochange。 Brieflydescribethelistcomprehension,andlearnmoreaboutitinthenextarticle。 Toputitsimply,relativelysimplesentencesareusedtoimplementmorecomplexfunctions。 Simpleexample,squarethenumberfrom1to10andaddittothelist。Theuseofdeductioncanberealizedinonesentence。 参考资料:python程序设计基础(董付国) 翻译:Google翻译 本文由LearningYard新学苑原创,部分图片文字来自网络,如有侵权请联系。