最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中l(wèi)ist列表的一些進階使用方法介紹

 更新時間:2015年08月15日 11:45:01   作者:老齊Py  
這篇文章主要介紹了Python中l(wèi)ist列表的一些進階使用方法介紹,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下

判斷一個 list 是否為空

傳統(tǒng)的方式:

if len(mylist):
  # Do something with my list
else:
  # The list is empty

由于一個空 list 本身等同于 False,所以可以直接:

if mylist:
  # Do something with my list
else:
  # The list is empty

遍歷 list 的同時獲取索引

傳統(tǒng)的方式:

i = 0
for element in mylist:
  # Do something with i and element
  i += 1

這樣更簡潔些:

for i, element in enumerate(mylist):
  # Do something with i and element
  pass

list 排序

在包含某元素的列表中依據(jù)某個屬性排序是一個很常見的操作。例如這里我們先創(chuàng)建一個包含 person 的 list:

class Person(object):
  def __init__(self, age):
    self.age = age

persons = [Person(age) for age in (14, 78, 42)]

傳統(tǒng)的方式是:

def get_sort_key(element):
  return element.age

for element in sorted(persons, key=get_sort_key):
  print "Age:", element.age

更加簡潔、可讀性更好的方法是使用 Python 標(biāo)準(zhǔn)庫中的 operator 模塊:

from operator import attrgetter

for element in sorted(persons, key=attrgetter('age')):
  print "Age:", element.age

attrgetter 方法優(yōu)先返回讀取的屬性值作為參數(shù)傳遞給 sorted 方法。operator 模塊還包括 itemgetter 和 methodcaller 方法,作用如其字面含義。

list解析

python有一個非常有意思的功能,就是list解析,就是這樣的:

>>> squares = [x**2 for x in range(1,10)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81]

看到這個結(jié)果,看官還不驚嘆嗎?這就是python,追求簡潔優(yōu)雅的python!

其官方文檔中有這樣一段描述,道出了list解析的真諦:

    List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

還記得前面一講中的那個問題嗎?

    找出100以內(nèi)的能夠被3整除的正整數(shù)。

我們用的方法是:

aliquot = []

for n in range(1,100):
  if n%3 == 0:
    aliquot.append(n)

print aliquot

好了。現(xiàn)在用list解析重寫,會是這樣的:

>>> aliquot = [n for n in range(1,100) if n%3==0]
>>> aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

震撼了。絕對牛X!

其實,不僅僅對數(shù)字組成的list,所有的都可以如此操作。請在平復(fù)了激動的心之后,默默地看下面的代碼,感悟一下list解析的魅力。

>>> mybag = [' glass',' apple','green leaf ']  #有的前面有空格,有的后面有空格
>>> [one.strip() for one in mybag]       #去掉元素前后的空格
['glass', 'apple', 'green leaf']

enumerate

這是一個有意思的內(nèi)置函數(shù),本來我們可以通過for i in range(len(list))的方式得到一個list的每個元素編號,然后在用list[i]的方式得到該元素。如果要同時得到元素編號和元素怎么辦?就是這樣了:

>>> for i in range(len(week)):
...   print week[i]+' is '+str(i)   #注意,i是int類型,如果和前面的用+連接,必須是str類型
... 
monday is 0
sunday is 1
friday is 2

python中提供了一個內(nèi)置函數(shù)enumerate,能夠?qū)崿F(xiàn)類似的功能

>>> for (i,day) in enumerate(week):
...   print day+' is '+str(i)
... 
monday is 0
sunday is 1
friday is 2

算是一個有意思的內(nèi)置函數(shù)了,主要是提供一個簡單快捷的方法。

官方文檔是這么說的:

    Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

順便抄錄幾個例子,供看官欣賞,最好實驗一下。

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

相關(guān)文章

最新評論

施秉县| 武宁县| 库车县| 林周县| 白山市| 沂南县| 宾川县| 潞城市| 藁城市| 石家庄市| 襄汾县| 固原市| 略阳县| 乐亭县| 灌阳县| 康平县| 洛扎县| 长汀县| 曲松县| 沧源| 凤翔县| 扬中市| 静乐县| 南丰县| 措美县| 天津市| 神池县| 廊坊市| 吉水县| 金川县| 迁西县| 乐亭县| 探索| 铁岭县| 宁都县| 上蔡县| 仁布县| 佛教| 莫力| 霍州市| 邹城市|