如何在PYTHON进行数据的遍历

2025-10-09 04:35:54

1、打开JUPYTER NOTEBOOK,新建一个空白的PY文档。

如何在PYTHON进行数据的遍历

2、list1 = ["Ben" , "Peter", "Alice"]

for l in list1:

    print(l)

新建一个列表,可以对列表这样进行遍历。

如何在PYTHON进行数据的遍历

3、dict1 = {"Ben": 99 , "Peter": 83, "Alice": 63}

for k in dict1:

    print(k)

字典比较特殊,如果这样遍历,只看到关键词。

如何在PYTHON进行数据的遍历

4、for k in dict1:

    print(dict1[k])

而这样就可以调出对应的值。

如何在PYTHON进行数据的遍历

5、for k in dict1:

    print("The key is %s and the value is %d." %(k, dict1[k]))

一般可以这样来一起调用两个数据。

如何在PYTHON进行数据的遍历

6、list2 = [

    {"Height": 187,

     "Check": "Yes",

     "S": "Femal"}

]

for l2 in list2:

    print(l2)

列表里面的字典,也是可以这样遍历的。

如何在PYTHON进行数据的遍历

7、ll = [{"First":"Ben", "Second": "Peter", "Third":"Alice"}, {"Fouth": "Chris", "Fifth": "Sing", "Sixth": "Leaf"}]

for lll in ll:

    print(lll)

列表里面有多种数据类型也是没问题的。

如何在PYTHON进行数据的遍历

8、for i in range(5, 18):

    print(i)

还可以定义范围来进行遍历。

如何在PYTHON进行数据的遍历

9、tuple1 = (32, 932, "Ben")

for t in tuple1:

    print(t)

元组的遍历方法和列表是一样的。

如何在PYTHON进行数据的遍历

10、dict1 = {"Ben": 99 , "Peter": 83, "Alice": 63}

for key, value in dict1.items():

    print("Key is %s and Value is %s" %(key, value))

这是另外一种遍历字典的方法,也很常见。

如何在PYTHON进行数据的遍历

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢