1. 程式人生 > >Python(五)

Python(五)

列表


@font-face { font-family: "Times New Roman"; }@font-face { font-family: "宋體"; }p.MsoNormal { margin: 0pt 0pt 0.0001pt; text-align: justify; font-family: 'Times New Roman'; font-size: 10.5pt; }p.p { margin: 5pt 0pt; text-align: left; font-family: 'Times New Roman'; font-size: 12pt; }span.msoIns { text-decoration: underline; color: blue; }span.msoDel { text-decoration: line-through; color: red; }div.Section0 { page: Section0; }

數組

數組存儲的是同一類型的一串信息

列表

一、列表的定義

? 定義一個空列表

list = []

? 定義一個包含元素的列表,元素可以是任意類型,包括數值類型,列表,元組,字符串等等均可。

賦值方式定義:

list = ["fentiao", 4, 'gender']

list1 = ['fentiao',(4,'male')]

工廠函數定義:

n = list("hello")

In [2]: n=list("hello")

In [3]: print n

['h', 'e', 'l', 'l', 'o']

二、支持索引、切片、拼接、重復、成員操作符

索引、切片:

In [4]: li=[1,1.0,True,'hello',1+4j,[1,2,"hello"]]

In [5]: li[0]

Out[5]: 1

In [6]: li[-1]

Out[6]: [1, 2, 'hello']

In [7]: li[:]

Out[7]: [1, 1.0, True, 'hello', (1+4j), [1, 2, 'hello']]

In [8]: li[1:]

Out[8]: [1.0, True, 'hello', (1+4j), [1, 2, 'hello']]

In [9]: li[0:2]

Out[9]: [1, 1.0]

In [10]: li[::-1]

Out[10]: [[1, 2, 'hello'], (1+4j), 'hello', True, 1.0, 1]

拼接:

In [18]: li1=['vsftpd','apache']

In [19]: li2=['mariadb','nfs']

In [20]: li1 + li2

Out[20]: ['vsftpd', 'apache', 'mariadb', 'nfs']

重復:

In [21]: li1=['vsftpd','apache']

In [22]: li1*2

Out[22]: ['vsftpd', 'apache', 'vsftpd', 'apache']

成員操作符:

In [23]: li1=['vsftpd','apache']

In [24]: 'vsftpd' in li1

Out[24]: True

In [25]: 'vsftpd' not in li1

Out[25]: False

題目1

查看1-10號主機的21,22,3306,80,69端口

解答:

#!/usr/bin/env python
# coding:utf-8
ports = [21,22,3306,80,69]
for i in range(1,11):
for port in ports: #可以通過 for i in list進行遍歷列表中的各個元素
ip = '172.25.254.'+str(i)
print "[+] Listening On:%s:%d" %(ip,port)

三、列表的常用方法

1.更新列表

append(增加一個元素)

extend(可以增加多個元素,可以在括號中給出一個列表,這個列表中的元素會倒入到原列表,成為他的元素)

@font-face { font-family: "Times New Roman"; }@font-face { font-family: "宋體"; }p.MsoNormal { margin: 0pt 0pt 0.0001pt; text-align: justify; font-family: 'Times New Roman'; font-size: 10.5pt; }p.p { margin: 5pt 0pt; text-align: left; font-family: 'Times New Roman'; font-size: 12pt; }span.msoIns { text-decoration: underline; color: blue; }span.msoDel { text-decoration: line-through; color: red; }div.Section0 { page: Section0; }

技術分享圖片


Python(五)