python 《第二谈》

环境:mac os x

1、创建简单的python列表

先从简单的颜色列表入手:
white
black
blue
red
yellow
上面列表,用python能理解的方式来写:
colors = ["white",
          "black",
          "blue",
          "red",
          "yellow"]

为了把人可读的列表转换成python可读的列表,需要遵循以下四个步骤:

1.在数据两边加引号,将各个颜色名称转换成字符串。

2.用逗号将列表项与下一项分隔开。

3.在列表的俩边加上开始和结束中括号。

4.使用赋值操作符(=)将这个列表赋值一个标识符(以上代码中的colors)。

$ colors = ["white",
          "black",
          "blue",
          "red",
          "yellow"]
列表就像是数组:在colos中,white是第0项、black是第1项…

2、访问列表数据

1) 打印列表中所有数据
$ print(colors)

$ print(colors)

[‘white’, ‘black’, ‘blue’, ‘red’, ‘yellow’]

2) 打印列表中单个数据,使用中括号偏移量记法访问列表数据
$ print(colors[1])

$ print(colors[1])

black

3) 得到列表中含有多少个数据项
$ print(len(colors))

$ print(len(colors))

5

3、编辑列表

1) 在列表末尾增加一个数据项 append()
$ colors.append("green")

$ colors.append(“green”)

$ print(len(colors))

6

2) 从列表末尾删除一个数据项 pop()
$ colors.pop()

$ colors.pop()

‘green’

$ print(len(colors))

5

3) 在列表末尾增加一个数据项集合 extend()
$ colors.extend(["green","gray"])

$ colors.extend([“green”,”gray”])

$ print(colors)

[‘white’, ‘black’, ‘blue’, ‘red’, ‘yellow’, ‘green’, ‘gray’]

4) 在列表某个特定的位置增加一个数据项 insert()
$ colors.insert(1,"orange")

$ colors.insert(1,”orange”)

$ print(colors)

[‘white’, ‘orange’, ‘black’, ‘blue’, ‘red’, ‘yellow’, ‘green’, ‘gray’]

5) 在列表删除一个特定的数据项 remove()
$ colors.remove("orange")

$ colors.remove(“orange”)

$ print(colors)

[‘white’, ‘black’, ‘blue’, ‘red’, ‘yellow’, ‘green’, ‘gray’]

3、处理列表数据

1) 迭代列表 for in
for 目标标识符 in 列表: //冒号放在列表名称后:指示列表处理代码开始
    列表处理代码
    
$ for each_color in colors:
    print(each_color)

$ for each_color in colors:

print(each_color)

white

black

blue

red

yellow

green

gray

注:使用for循环是可伸缩的,适用于任意大小的列表。

2) 迭代列表 while
$  count = 0    
$  while count < len(colors):
    print(colors[count])
    count = count + 1
    

count = 0

$ while count < len(colors):

print(colors[count])

count = count + 1

white

black

blue

red

yellow

green

gray

4、列表嵌套列表

1) 定义一个列表,并嵌套列表
$ colors = ["white",
         "red",
         "black",
         ["#fff","#ff2600","#000"]]
$ print(colors)

$ colors = [“white”,”red”,”black”,[“#fff”,”#ff2600″,”#000″]]

$ print(colors)

[‘white’, ‘red’, ‘black’, [‘#fff’, ‘#ff2600’, ‘#fff’]]

2) 往列表中,插入添加另一个列表
    
$ colors = ["white",
            "red",
            "black"]
$ colors1 = ["#fff",
             "#ff2600",
             "#000"]
$ colors.append(colors1)
$ print(colors)

$ colors = [“white”,”red”,”black”]

$ colors1 = [“#fff”,”#ff2600″,”#000″]

$ colors.append(colors1)

$ print(colors)

[‘white’, ‘red’, ‘black’, [‘#fff’, ‘#ff2600’, ‘#fff’]]

5、复杂数据处理

1) 处理嵌套列表
$ for each_color in colors:
    if isinstance(each_color,list):
        for nest_color in each_color:
            print(nest_color)
    else:
        print(each_color)

white

red

black

#fff

#ff2600

#fff

    原文作者:怪咖先森_zys
    原文地址: https://www.jianshu.com/p/54eb088ca3c8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞