美文网首页优雅的大蟒蛇——Python
对python中list的一些使用体会

对python中list的一些使用体会

作者: 帕博雷克斯丢丢 | 来源:发表于2018-03-19 10:31 被阅读0次

    问题:如何用一个字符串快速生成列表?

    • 最直接最新手最菜的办法当然是用for循环遍历str并加入[]中。
    str1 = "hello"
    list1 = []
    for i in str:
        list1.append(i)
    print(list1)
    
    • 最好最简洁的办法当然是用列表生成式:
    str1 = "hello"
    list1 = [i for i in str1]
    

    然后,又有了新的问题:

    • 我们有时候会同时引用两个变量去迭代Iterable对象,例如:
    for k, v in {'c': 86, 'j': 81, 'k': 82}.items():
        print("%s---%d" % (k, v))
    
    • 那么,可以同时引用三个、四个甚至更多的变量吗?

    下面是实验代码:

    lt = [(11, 13, 15), (21, 23, 25), (31, 33, 35)]
    for i, j, k in lt:
        print("{} - {} - {}".format(i, j, k))
    

    输出结果:

    11 - 13 - 15
    21 - 23 - 25
    31 - 33 - 35
    

    Perfect!完美。那么四个变量五个变量就不用试了。

    相关文章

      网友评论

        本文标题:对python中list的一些使用体会

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