python - tuples

作者: Pingouin | 来源:发表于2020-09-03 18:14 被阅读0次

    tuples

    tuples are like lists, they have elements which are indexed starting at 0

    x = ('ke','is','sleepy')
    print(x[2])
    y = (1,2,3)
    print(y[0])
    print(max(y))
    

    Why tuples (an immutable list)?

    The immutable list provides a data structure with some integrity and some persistence. It is not possible to accidentally change a tuple.

    tuples are immutable!!

    • things not to do with tuples:
    x = (1,2,3)
    x.sort()
    x.append()
    x.reverse()
    
    # 与list比较可以用的函数
    l = list()
    t = tuple()
    dir(l)
    dir(t) # count , index
    

    tuples are more efficient

    tuples and assignment

    • we can also put a tuple on the left-hand side of an assignment statement
    (x,y) = (1, 'ke')
    print(y)
    (a,b) = (22,33)
    print(a)
    

    tuples and dictionaries

    d = dict()
    d['1'] = 1
    d['2'] = 2
    for (k,v) in d.items():
      print(k,v)
    tups = d.items()
    print(tups)
    

    tuples are comparable

    • if the first item is equal, go to the second item to compare until it finds the element that differs. 只要比较了一个了,后面的就不需要比较

    sorting lists of tuples

    1. first, we sort the dictionary by the key using the items() method and sorted() function.
    d = {'a':22, 'h':11, 'f':22}
    d.items()
    sorted(d.items(),reverse = True)
    

    it's also possible to sort by values instead of key: construct a list of tuples of the form (value, key) we could sort by value.

    1. sort a tuple by sorted method, then it returns a list. So we need to convert it back to a tuple.
    sorted_list = sorted(a_tuple)
    new_tuple = tuple(sorted_list)
    

    top10 most common

    d = {'a':22, 'h':11, 'f':22}
    print(sorted([(v,k) for k,v in d.items()]))
    

    相关文章

      网友评论

        本文标题:python - tuples

        本文链接:https://www.haomeiwen.com/subject/yhcisktx.html