美文网首页
List, Set, and Dict Comprehensio

List, Set, and Dict Comprehensio

作者: 闫_锋 | 来源:发表于2018-12-03 16:27 被阅读8次

    List Comprehensions

    In [154]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
    In [155]: [x.upper() for x in strings if len(x) > 2]
    Out[155]: ['BAT', 'CAR', 'DOVE', 'PYTHON']
    

    Set Comprehensions

    In [156]: unique_lengths = {len(x) for x in strings}
    In [157]: unique_lengths
    Out[157]: {1, 2, 3, 4, 6}
    

    Dict Comprehension

    In [158]: set(map(len, strings))
    Out[158]: {1, 2, 3, 4, 6}
    
    In [159]: loc_mapping = {val : index for index, val in enumerate(strings)}
    In [160]: loc_mapping
    Out[160]: {'a': 0, 'as': 1, 'bat': 2, 'car': 3, 'dove': 4, 'python': 5}
    

    相关文章

      网友评论

          本文标题:List, Set, and Dict Comprehensio

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