Python学习之基本数据类型 集合

4.6.4. Lists

Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).
翻译:lists都是可变的序列,经常被用来存储同类元素集合(同层次的元素将会被程序进行分类)

class  list ( [ iterable ] )

Lists may be constructed in several ways:

  • Using a pair of square brackets to denote the empty list: []
  • Using square brackets, separating items with commas: [a][a, b, c]
  • Using a list comprehension: [x for x in iterable]
  • Using the type constructor: list() or list(iterable)

翻译:这些集合可能以下面这几种方式进行构建:
        通过中括号对来构建构建一个空的集合:[] 
        通过中括号对,用逗号分隔元素:[a][a, b, c]
        通过列表推导式来构建:[x for x in iterable]
        通过构造方法进行构建: list() or list(iterable)
The constructor builds a list whose items are the same and in the same order as iterable’s items. iterablemay be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] andlist( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].
翻译:构造方法创建出来的集合和iteratble里面的元素是一样的,并且排序也是一样的。iterable可能是一个序列或者是一个容器支持迭代,或者是一个iterator对象,如果iterable已经是一个集合,那么就会拷贝一份并返回,和iterable[:] 类似。比如list('abc') returns ['a', 'b', 'c'] 然后list( (1, 2, 3) ) returns [1, 2, 3] 。如果没有参数,那么构造方法就会创建一个空的集合。

Many other operations also produce lists, including the sorted() built-in.
翻译:许多的操作都会生成集合,比如说系统函数sorted

Lists implement all of the common and mutable sequence operations. Lists also provide the following additional method:
翻译:集合实现了所有普通的以及可变序列的方法,集合也提供了额外的方法。

sort ( *key=Nonereverse=False )

This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).
翻译:这个方法会对集合进行排序,在元素之间只使用<进行比较运算。异常将不会被处理,如果任何比较操作运算失败,整个排序操作都将失败(集合将处于被修改部分后的状态)

sort() accepts two arguments that can only be passed by keyword (keyword-only arguments):
翻译:方法接受两个参数,而且只能通过关键字进行传递(key=,reverse=)

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.
翻译:key指定了一个方法参数,这个参数被用来指定两个item之间的比较关系(比如key=str.lower)。key将会对参数集合中每一个项只会计算一次,然后进行排序运算。默认值None表达的意思是:每一个项都将会直接用于排序,不进行其他的任何计算。

The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function.

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
翻译:reverse参数是一个bool值,如果设置为True,那么list在排序后,会对颠倒顺序(升序降序)

This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use sorted() to explicitly request a new sorted list instance).
翻译:这个方法将会修改这个序列,当集合的元素太大时,会采用一种经济有效的方式进行。需要提醒的是这个操作是内部操作,不会返回排序后的序列。使用sorted方法来获取一个排序后的序列对象。

The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
翻译:sort这个方法是稳定的排序。稳定的排序就是在排序前后不会修改集合中的相对位置。这种排序对于多规则排序是很有效的。(比如:按照部门排序,然后在部门相同的情况下按照业绩排序)

CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.
翻译:当集合被排序的时候,在这个过程中进行修改。或者是查看,这个集合抛出未定义。python继承c接口的时候造成了排序途中会编程一个空集合,如果在排序过程中可以检测出修改了数据,就会抛出valueError异常。(在排序过程中会有一定的耗时,如果在这个过程中进行其他操作,比如增删查改,会出现不确定的异常。)

我们将在这里演示一下排序。

def cmp(value=None):
    print(value)
    if isinstance(value,int):
        return value
    else:
        return -1
list_test =  [0,2,4,6,8,10,1,3,5,7,9,11,"aa","bb","cc","dd",6.5]
list_test.sort(key=cmp)
print(list_test)

输出

0
2
4
6
8
10
1
3
5
7
9
11
aa
bb
cc
dd
6.5
['aa', 'bb', 'cc', 'dd', 6.5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

我们将会对类进行排序

class Student():
    def __init__(self,chinese=0,math=0,english=0):
        self.__chinese=chinese
        self.__math = math
        self.__english = english
    def __lt__(self, other):
        self_sum = self.__sum__()
        other_sum = other.__sum__()
        if self_sum != other_sum :
            return self_sum<other_sum
        elif self_sum == other_sum:
            if self.__chinese != other.__chinese:
                return self.__chinese < other.__chinese
            if self.__math != other.__math:
                return self.__math < other.__math
            if self.__english != other.__english:
                return self.__english < other.__english
            return 0
    def __sum__(self):
        return self.__chinese+self.__math+self.__english
    def __str__(self):
        return str(self.__chinese)+str(self.__math)+str(self.__english)

students = [Student(145,132,112),Student(105,132,112),
            Student(125,130,122),Student(144,131,100),
            Student(95,102,102),Student(105,92,102),
            Student(145,142,132),Student(132,112,145),
            Student(140,132,112),Student(115,132,112),]

students.sort()
for i in students:
    print(i.__sum__(),i._Student__chinese,i._Student__math,i._Student__english)

输出

299 95 102 102
299 105 92 102
349 105 132 112
359 115 132 112
375 144 131 100
377 125 130 122
384 140 132 112
389 132 112 145
389 145 132 112
419 145 142 132
我们可以看到,这里是按照总分排名,然后如果分数相同按照语数英的高低进行排名






猜你喜欢

转载自blog.csdn.net/rubikchen/article/details/80670404