跳至主要内容

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...

MechanicalSoup

用于自动与网站交互的 Python 库。 MechanicalSoup 自动存储和发送 cookie,跟踪重定向,并且可以跟踪链接和提交表单。 它不执行 JavaScript。 https://github.com/MechanicalSoup/MechanicalSoup https://mechanicalsoup.readthedocs.io/en/stable/index.html https://realpython.com/python-web-scraping-practical-introduction/ pip show Mechanicalsoup 找到模块的安装位置 https://stackoverflow.com/questions/54352162/download-file-with-mechanicalsoup # Install dependencies # pip install requests # pip install BeautifulSoup4 # pip install MechanicalSoup # Import libraries import mechanicalsoup import urllib.request import requests from bs4 import BeautifulSoup import re # Create a browser object that can collect cookies browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/l2kq/qna") browser.download_link(link_text=".xls",file="D:/ONS_Data.xls" )

Chrome浏览器

谷歌搜索 双引号——精确搜索 冒号后加文件类型——搜索特定类型的结果 关键词 后 site:**——搜索特定网站的关键词 +、-关键词——实现特定需求筛选 Google中/——快捷键入浏览·搜索框 关键词后..——搜索特定范围(地点)关键词 intitle:关键词——搜索特定标题 用 puppeteer 直接运行 chrome 爬 https://github.com/puppeteer/puppeteer Puppeteer 是一个 Node 库,它提供了一个高级 API 来通过 DevTools 协议 控制 Chrome 或 Chromium 。Puppeteer默认 无头 运行,但可以配置为运行完整(非无头)Chrome 或 Chromium。 了解如何为 Chrome 开发扩展程序 https://developer.chrome.com/docs/extensions/mv3/ 什么是Chrome插件 https://github.com/sxei/chrome-plugin-demo Google Workspace 状态信息中心 https://www.google.com/appsstatus#hl=zh&v=status 此页面提供属于“Google Workspace”的服务的状态信息 谷歌浏览器离线下载 https://support.google.com/chrome/answer/95346?co=GENIE.Platform%3DDesktop&hl=zh-Hans 企业版 https://cloud.google.com/chrome-enterprise/browser/download 也可以在谷歌浏览器 帮助中心 中搜索chrome https://www.google.com/intl/zh-CN/chrome/?standalone=1 chrome 打开新网页时不要覆盖 鼠标 中键(滚轮)点击超链接 ,或者右击超链接,选择新标签页打开, 还有点链接的同时按下 Ctrl 键也可以 谷歌在线翻译网页 http://translate.google.com/translate?u= http://www.dropitproject.com/index.php 打开chrome浏览器按 F6 ,等同于按 ...