美文网首页
Python列的推导式,遍历的技巧

Python列的推导式,遍历的技巧

作者: 黄褐色猫头鹰 | 来源:发表于2018-11-07 10:42 被阅读0次
    #列的推导式, 如果需要推导出列表用中括号, 如果想推导出元组, 用小括号
    #基础版
    vec = [2, 4, 6]
    var_list1 = [3*x for x in vec]
    print(var_list1) #[6, 12, 18]
    
    #不一样的数据类型
    var_list2 = [[x, x**2] for x in vec]
    print(var_list2) #[[2, 4], [4, 16], [6, 36]]
    
    var_dic = {x: x**2 for x in (2, 4, 6)}
    print(var_dic) #{2: 4, 4: 16, 6: 36}
    
    #数据改变
    freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
    var_list3 = [weapon.strip() for weapon in freshfruit]
    print(var_list3) #['banana', 'loganberry', 'passion fruit']
    
    #条件判断
    var_list4 = [3*x for x in vec if x > 3]
    print(var_list4) #[12, 18]
    
    #多个遍历
    vec1 = [2, 4, 6]
    vec2 = [4, 3, -9]
    var_list5 = [x*y for x in vec1 for y in vec2] #笛卡尔积
    print(var_list5) #[8, 6, -18, 16, 12, -36, 24, 18, -54]
    
    var_list6 = [vec1[i]*vec2[i] for i in range(len(vec1))]
    print(var_list6) #[8, 12, -54]
    
    #嵌套列表的一些技巧
    matrix = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
    ]
    #   矩阵的转置
    var_list7 = [[row[i] for row in matrix] for i in range(4)]
    print(var_list7) #[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    
    #字典遍历的技巧
    knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    for k, v in knights.items():
        print(k, v)
    
    #带有下标的遍历序列
    for i, v in enumerate(['tic', 'tac', 'toe']):
        print(i, v)
    
    #同时遍历多个序列
    questions = ['name', 'quest', 'favorite color']
    answers = ['lancelot', 'the holy grail', 'blue']
    for q, a in zip(questions, answers):
        print('What is your {0}?  It is {1}.'.format(q, a))
    
    #反向遍历序列
    for i in reversed(range(1, 20, 2)):
        print(i)
    
    #按指定顺序遍历序列, 且不修改原始值
    basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    for f in sorted(set(basket)):
        print(f)
    
    

    相关文章

      网友评论

          本文标题:Python列的推导式,遍历的技巧

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