跳至主要内容

python 之 List(列表)



模拟超市购物
  1. shopping_list = ['milk', 'yoghurt', 'egg', 'butter', 'bread', 'bananas']
  2. cart = []
  3. while shopping_list != []:
  4.     article = shopping_list.pop()  
  5.     cart.append(article)
  6.     print(article, shopping_list, cart)
  7.  
  8. print("shopping_list: ", shopping_list)
  9. print("cart: ", cart)
  10.  

letter salad

  1. s = "Toronto is the largest City in Canada"
  2. t = "Python courses in Toronto by Bodenseo"
  3. # print(list(zip(s,t)))
  4. ss = "".join(["".join(x) for x in zip(s,t)])
  5. print(ss) #TPoyrtohnotno  ciosu rtshees  lianr gTeosrto nCtiot yb yi nB oCdaennasdeao
  6. print(ss[::2]) #Toronto is the largest City in Canada
  7. print(ss[1::2]) #Python courses in Toronto by Bodenseo

重复的陷阱
  1. x = ["a","b","c"]
  2. y = [x] * 4
  3.  
  4. print(y)
  5. # [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
  6.  
  7. y[0][0] = "p"
  8.  
  9. print(y)
  10. # [['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c']]
  11.  

Python列表方法


列表方法   描述
append()   它将新元素添加到列表的末尾
extend()    它通过添加另一个列表、字符串、元组中的元素来扩展列表
insert()      它以所需的索引注入一个新元素,
lst.insert(index, object)
remove()   它从列表中删除所需的元素,lst.remove(x)
pop()         它从给定位置删除并返回一个项目,默认最后一项。
clear()       它删除列表的所有元素。
index()      它返回最先匹配的元素的索引。
lst.index("v")\lst.index("v",3)\lst.index("v",2,3)
count()     它返回总数。作为参数传递的元素。
sort()        它以递增的方式对列表的元素进行排序。
reverse()  它会反转列表中元素的顺序。
copy()      它执行列表的浅拷贝并返回。





Python列表内置函数

功能                  描述
all()                   如果列表包含具有True值的元素或为空,则返回True。
any()                 如果任何成员具有True值,则它也返回True。
enumerate()     它返回一个具有所有列表元素的索引和值的元组。
len()                  返回值是列表的大小。
list()                  它转换所有可迭代的对象并作为列表返回。
max()                具有最大值的成员
min()                 最小值的成员
sorted()             它返回列表的排序副本。
sum()                返回值是列表中所有元素的总和。


# 空白列表 
L1 = [] 
# 整数列表 
L2 = [10, 20, 30] 
# 异构数据类型列表 
L3 = [1, "Hello", 3.4]


创建一个空列表

>>> my_list = []
>>> my_list = list()


List()构造函数

Python包含一个内置的list()方法,又名构造函数,它接受序列或元组作为参数,然后转换为Python列表

>>> theList = list([1, 2, [1.1, 2.2]]) 
>>> theList 
[1, 2, [1.1, 2.2]] 
>>> len(theList) 
3

List Comprehension
列表推导


>>> theList = [iter for iter in range(5)] 
>>> print(theList) 
[0, 1, 2, 3, 4]


>>> listofCountries = ["India","America","England","Germany","Brazil","Vietnam"] 
>>> firstLetters = [ country[0] for country in listofCountries ] 
>>> print(firstLetters) 
['I', 'A', 'E', 'G', 'B', 'V']

>>> print ([x+y for x in 'get' for y in 'set']) 
['gs', 'ge', 'gt', 'es', 'ee', 'et', 'ts', 'te', 'tt']

>>> print ([x+y for x in 'get' for y in 'set' if x != 't' and y != 'e' ]) 
['gs', 'gt', 'es', 'et']


>>> months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] >>> oddMonths = [iter for index, iter in enumerate(months) if (index%2 == 0)] 
>>> oddMonths 
['jan', 'mar', 'may', 'jul', 'sep', 'nov']


>>> init_list = [0]*3 
>>> print(init_list) 
[0, 0, 0]


>>> two_dim_list = [ [0]*3 ] *3 
>>> print(two_dim_list) 
[[0, 0, 0], [0, 0, 0], [0, 0, 0]] 
>>> two_dim_list[0][2] = 1 
>>> print(two_dim_list) 
[[0, 0, 1], [0, 0, 1], [0, 0, 1]]


>>> two_dim_list = [[0]*3 for i in range(3)] 
>>> print(two_dim_list) 
[[0, 0, 0], [0, 0, 0], [0, 0, 0]] 
>>> two_dim_list[0][2] = 1 
>>> print(two_dim_list) 
[[0, 0, 1], [0, 0, 0], [0, 0, 0]]

列表扩展


>>> L1 = ['a', 'b']
>>> L2 = [1, 2]
>>> L3 = ['Learn', 'Python']
>>> L1 + L2 + L3
['a', 'b', 1, 2, 'Learn', 'Python']


>>> L1 = ['a', 'b']
>>> L2 = ['c', 'd']
>>> L1.extend(L2)
>>> print(L1)
['a', 'b', 'c', 'd']


>>> L1 = ['x', 'y']
>>> L1.append(['a', 'b'])
>>> L1
['x', 'y', ['a', 'b']]



列表切片

Python附带了一个神奇的slice运算符,该运算符返回序列的一部分。它对不同数据类型的对象( 例如字符串,元组)进行操作,并且在Python列表上的工作原理相同。


复制列表

>>> id(theList)
55530056
>>> id(theList[::])
55463496



for index, element in enumerate(theList):
    print(index, element)


for index in range(len(theList)):
    print(index)



it = iter(theList)
element = it.next() # fetch first value 
element = it.next() # fetch second value




theList = ['a','e','i','o','u']
newList = sorted(theList, reverse=True)
print("Original list:", theList, "Memory addr:", id(theList))
print("Copy of the list:", newList, "Memory addr:", id(newList))
# Original list: ['a', 'e', 'i', 'o', 'u'] Memory addr: 120082568 

# Copy of the list: ['u', 'o', 'i', 'e', 'a'] Memory addr: 120086216



列表更新
list[0]=1

列表删除元素
有3种Python方法:list.remove(),list.pop()和del运算符
list.remove("v")
list.pop(0)

del list[0]

#列表添加
a = [] 
for x in range(0,10): 
  a.append(x) 
print(a) 

# List Comprehension 
#列表推导
print([x for x in a]) 


list_of_squares_2 = [int**2 for int in range(1, 10)]


len(list) 返回列表长度
numbers = [2, 5, 7, 9]
print(len(numbers))
>>> 4
max(list)返回列表中的最大值
numbers = [2, 5, 7, 9]
print(max(numbers))
>>> 9
min(list):返回列表中的最小值
numbers = [2, 5, 7, 9]
print(min(numbers))
>>> 2
list(tuple):将一个元组对象转换为一个列表
animals = ('cat', 'dog', 'fish', 'cow')
print(list(animals))
>>> ['cat', 'dog', 'fish', 'cow']
list.append(element):将元素追加到列表中
numbers = [2, 5, 7, 9]
numbers.append(15)
print(numbers)
>>> [2, 5, 7, 9, 15]
list.pop(index):从列表中删除指定索引处的元素,默认最后一项
numbers = [2, 5, 7, 9, 15]
numbers.pop(2)
print(numbers)
>>> [2, 5, 9, 15]
list.remove(element):从列表中删除元素
values = [2, 5, 7, 9]
values.remove(2)
print(values)
>>> [5, 7, 9]
list.reverse():反转列表的对象
values = [2, 5, 7, 10]
values.reverse()
print(values)
>>> [10, 7, 5, 2]
list.index(element):获取列表中元素的索引值
animals = ['cat', 'dog', 'fish', 'cow', 'goat']
fish_index = animals.index('fish')
print(fish_index)
>>> 2
sum(list):获取列表中所有值的总和,如果值都是数字(整数或小数)
values = [2, 5, 10]
sum_of_values = sum(values)
print(sum_of_values)
>>> 17
list.sort():按升序或降序排列整数,浮点数或字符串的列表
values = [1, 7, 9, 3, 5]
# To sort the values in ascending order:
values.sort()
print(values)
>>> [1, 3, 5, 7, 9]

values = [2, 10, 7, 14, 50]
# To sort the values in descending order:
values.sort(reverse = True)
print(values)
>>> [50, 14, 10, 7, 2]
# to sort the list by length of the elements
strings = ['cat', 'mammal', 'goat', 'is']
strings.sort()
print(strings)
strings.sort(key = len)
print(strings)

评论

此博客中的热门博文

学习地址

清华大学计算机系课程攻略 https://github.com/PKUanonym/REKCARC-TSC-UHT 浙江大学课程攻略共享计划 https://github.com/QSCTech/zju-icicles https://home.unicode.org/ 世界上的每个人都应该能够在手机和电脑上使用自己的语言。 http://codecanyon.net   初次看到这个网站,小伙伴们表示都惊呆了。原来代码也可以放在网上卖的?!! 很多coder上传了各种代码,每个代码都明码标价。看了下销售排行,有的19刀的卖了3万多份,额di神啊。可以看到代码的演示效果,真的很漂亮。代码以php、wordpress主题、Javascript、css为主,偏前台。 https://www.lintcode.com/ 算法学习网站,上去每天刷两道算法题,走遍天下都不怕。 https://www.codecademy.com/ 包含在线编程练习和课程视频 https://www.reddit.com/ 包含有趣的编程挑战题,即使不会写,也可以查看他人的解决方法。 https://ideone.com/ 在线编译器,可运行,可查看代码示例。 http://it-ebooks.info/ 大型电子图书馆,可即时免费下载书籍。 刷题 https://github.com/jackfrued/Python-100-Days https://github.com/kenwoodjw/python_interview_question 面试问题 https://github.com/kenwoodjw/python_interview_question https://www.journaldev.com/15490/python-interview-questions#python-interpreter HTTP 身份验证 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Authentication RESTful 架构详解 https://www.runoob.com/w3cnote/restful-architecture.html https://www.rosettacode.org/wiki/Rosetta_C...

PDF处理

虚拟pdf打印机 pdfFactory  https://fineprint.com PDFCreator  https://www.pdfforge.org 开源 cutepdf https://www.cutepdf.com/index.htm Doro PDF Writer http://www.the-sz.com/products/doro PdfScribe  https://github.com/stchan/PdfScribe/releases pdf阅读器 Sumatra PDF https://www.sumatrapdfreader.org/ 为什么 Python 用于 PDF 处理  如您所知,PDF 处理属于文本分析。 大多数文本分析库或框架仅使用 Python 设计。 这为文本分析提供了优势。 还有一件事,您永远无法在现有的机器学习或自然语言处理框架中直接处理 pdf。 除非他们为此证明了显式接口。 我们必须先将pdf转换为文本。 我们可以使用下述任何库轻松实现这一点。 在线转换pdf Sejda https://www.sejda.com/pdf-editor 每个文档 200 页的免费限制 https://www.pdf2go.com/ https://tools.pdfforge.org/extract-text PDF24 Tools https://tools.pdf24.org/zh/ 免费且易于使用的在线PDF工具 FreeOCR http://www.paperfile.net/ 适用于Windows的免费光学字符识别软件,支持大多数Twain扫描仪的扫描,还可以打开大多数扫描的PDF和多页Tiff图像以及流行的图像文件格式,FreeOCR输出纯文本,可以直接导出为Microsoft Word格式。 不支持中文 wkhtmltopdf 和 wkhtmltoimage 是使用 QT Webkit 渲染引擎将 HTML 渲染为 PDF 和各种图像格式的命令行工具。这些完全“无头”运行,不需要显示或显示服务。 https://wkhtmltopdf.org/ django-wkhtmltopdf 允许 Django 站点输出动态 PDF。它利用 wkhtmltopdf 库,允许您使用您知道...

端口映射 公网访问内网

https://portforward.com/ Holer 通过安全隧道将位于NAT和防火墙之后的本地服务器暴露给公共Internet。 Holer是一个将原型中的应用映射到公网访问的端口映射软件,支持转发基于TCP协议的报文 https://github.com/wisdom-projects/holer 方式一:使用(公告)的holer映射或者开通holer服务,通过holer客户端软件经 holer服务器实现公网访问。 公开的holer映射详情如下: 访问密钥 访问域名 公网地址 本地地址 使用场景 HOLER_CLIENT-2F8D8B78B3C2A0AE holer65530.wdom.net holer.org:65530 127.0.0.1:8080 网页 HOLER_CLIENT-3C07CDFD1BF99BF2 holer65531.wdom.net holer.org:65531 127.0.0.1:8088 网页 HOLER_CLIENT-2A623FCB6E2A7D1D holer65532.wdom.net holer.org:65532 127.0.0.1:80 网页 HOLER_CLIENT-AF3E6391525F70E4 不适用 holer.org:65533 127.0.0.1:3389 远程桌面 HOLER_CLIENT-822404317F9D8ADD 不适用 holer.org:65534 127.0.0.1:22 SSH协议 HOLER_CLIENT-27DD1389DF1D4DBC 不适用 holer.org:65535 127.0.0.1:3306 数据库 使用Java版本的holer客户端 ①java 1.7或者更高版本 ②下载holer-client.zip 修改配置文件C:\holer-client\conf\holer.conf HOLER_ACCESS_KEY=HOLER_CLIENT-2A623FCB6E2A7D1D HOLER_SERVER_HOST=holer65532.wdom.net ③建议先双击运行C:\holer-client\bin\shutdown.bat,再双击运行C:\holer-client\bin\startup.bat...