python while使用方法_Python中list列表使用方法总结

更新时间:2019-12-26    来源:python    手机版     字体:

【www.bbyears.com--python】


list列表extend()使用方法


extend()使用方法
与一般函数调用格式一样,变量名.方法名(参数)

extend方法可以在列表尾部追加包含多个值的另一个序列,而list的append()只能添加一个值。可以说list的extend方法是有扩展列表的作用:
>>> list1 = [1,2,3]
>>> list2 = [7,8,9]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 7, 8, 9]
list2中包含多个元素,被一次性添加到了list1中。

extend()和加号+连接操作符的区别
这个操作结果和用+号连接操作很像,但两者是有本质区别的。extend方法是把元素添加到了list1中,相当于扩展(修改)list1的数据,但id没有改变。如果用+号连接的话,它返回的是一个新生成的列表:
>>> list1 = [1,2,3]
>>> list2 = [7,8,9]
>>> list1 + list2
[1, 2, 3, 7, 8, 9]
>>> list1
[1, 2, 3]

list1 + list2虽然看上去显示的结果和extend方法一样,但其实它得到的是一个新列表,不能被引用的值。
如果要引用这个list1 + list2的结果需要将它赋一个变量名,比如:list1 = list1 + list2,此时再输出list1的结果就会是[1, 2, 3, 7, 8, 9]了。但它的工作效果远不如extend方法高。

 

判断一个 list 是否为空

传统的方式:

[py] view plaincopy
if len(mylist): 
  # Do something with my list 
else: 
  # The list is empty 


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

[py] view plaincopy
if mylist: 
  # Do something with my list 
else: 
  # The list is empty 


遍历 list 的同时获取索引

传统的方式:

[py] view plaincopy
i = 0 
for element in mylist: 
  # Do something with i and element 
  i += 1 


这样更简洁些:

[py] view plaincopy
for i, element in enumerate(mylist): 
  # Do something with i and element 
  pass 


list 排序

在包含某元素的列表中依据某个属性排序是一个很常见的操作。例如这里我们先创建一个包含 person 的 list:

[py] view plaincopy
class Person(object): 
  def __init__(self, age): 
    self.age = age 
 
persons = [Person(age) for age in (14, 78, 42)] 


传统的方式是:

[py] view plaincopy
def get_sort_key(element): 
  return element.age 
 
for element in sorted(persons, key=get_sort_key): 
  print "Age:", element.age 


更加简洁、可读性更好的方法是使用 Python 标准库中的 operator 模块:

[py] view plaincopy
from operator import attrgetter 
 
for element in sorted(persons, key=attrgetter("age")): 
  print "Age:", element.age 


attrgetter 方法优先返回读取的属性值作为参数传递给 sorted 方法。operator 模块还包括 itemgetter 和 methodcaller 方法,作用如其字面含义。

list解析

python有一个非常有意思的功能,就是list解析,就是这样的:

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


看到这个结果,看官还不惊叹吗?这就是python,追求简洁优雅的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以内的能够被3整除的正整数。

我们用的方法是:

[py] view plaincopy
aliquot = [] 
 
for n in range(1,100): 
  if n%3 == 0: 
    aliquot.append(n) 
 
print aliquot 


好了。现在用list解析重写,会是这样的:

[py] view plaincopy
>>> 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!

其实,不仅仅对数字组成的list,所有的都可以如此操作。请在平复了激动的心之后,默默地看下面的代码,感悟一下list解析的魅力。

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


enumerate

这是一个有意思的内置函数,本来我们可以通过for i in range(len(list))的方式得到一个list的每个元素编号,然后在用list[i]的方式得到该元素。如果要同时得到元素编号和元素怎么办?就是这样了:

[py] view plaincopy
>>> 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中提供了一个内置函数enumerate,能够实现类似的功能

[py] view plaincopy
>>> for (i,day) in enumerate(week): 
...   print day+" is "+str(i) 
...  
monday is 0 
sunday is 1 
friday is 2 


算是一个有意思的内置函数了,主要是提供一个简单快捷的方法。

官方文档是这么说的:

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:

顺便抄录几个例子,供看官欣赏,最好实验一下。

[py] view plaincopy
>>> 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")] 


对list去重的多种方法


最简单的思路就是:

 

ids = [1,2,3,3,4,2,3,4,5,6,1]
news_ids = []
for id in ids:
    if id not in news_ids:
        news_ids.append(id)

print news_ids


这样也可行,但是看起来不够爽。

用set

另外一个解决方案就是用set:

 

ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))

这样的结果是没有保持原来的顺序。

按照索引再次排序

最后通过这种方式解决:

 

ids = [1,4,3,3,4,2,3,4,5,6,1]
news_ids = list(set(ids))
news_ids.sort(ids.index)

使用itertools.grouby

文章一开始就提到itertools.grouby, 如果不考虑列表顺序的话可用这个:

 

ids = [1,4,3,3,4,2,3,4,5,6,1]
ids.sort()
it = itertools.groupby(ids)

for k, g in it:
    print k


关于itertools.groupby的原理可以看这里:http://docs.python.org/2/library/itertools.html#itertools.groupby

网友补充:用reduce

网友reatlk留言给了另外的解决方案。我补充并解释到这里:

 

In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1]

In [6]: func = lambda x,y:x if y in x else x + [y]

In [7]: reduce(func, [[], ] + ids)
Out[7]: [1, 4, 3, 2, 5, 6]


上面是我在ipython中运行的代码,其中的 lambda x,y:x if y in x else x + [y] 等价于 lambda x,y: y in x and x or x+[y] 。

本文来源:http://www.bbyears.com/jiaocheng/83844.html

热门标签

更多>>

本类排行