跳至主要内容

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" )

安装和卸载软件(msi\exe)

如何判断一个软件是64位的还是32位的? 情况1、 未安装--右键安装程序查看属性,兼容性,勾选兼容模式查看最低适配是vista的是64位,反之32位, 不太准确 情况2、 已安装--运行软件,64位操作系统打开任务管理器看进程后缀名,带*32就是32位,反之64位 https://www.joci.net/xxbk/126251/ FileMon 和 Regmon 不再可供下载。从Windows 2000 SP4,Windows XP SP2,Windows Server 2003 SP1和Windows Vista开始的Windows版本上,它们已被 Process Monitor 取代 https://adamtheautomator.com/procmon/ Process Monitor 是Windows的高级监视工具,它显示实时文件系统,注册表和进程/线程活动。 它结合了两个旧的Sysinternals实用程序 Filemon 和  Regmon的功能 ,并添加了广泛的增强功能列表,包括丰富的和非破坏性的过滤,全面的事件属性(例如会话ID和用户名),可靠的过程信息,带有集成符号的完整线程堆栈支持每个操作,同时记录到文件等。 它独特的强大功能将使Process Monitor成为您的系统故障排除和恶意软件搜索工具包中的核心实用程序。 https://wikileaks.org/ciav7p1/cms/page_42991626.html HKLM\Software\Microsoft\Cryptography\MachineGuid Machine GUID/Cryptography GUID---该密钥通常用作机器的唯一标识符。它也已用于将两台计算机链接在一起-在某些情况下,计算机GUID是与设备(MP3播放器等)一起传递的。 Machine GUID不是唯一 https://docs.microsoft.com/zh-cn/windows/win32/properties/props-system-identity-uniqueid?redirectedfrom=MSDN UniqueID才是唯一 注册表 是存储系统和应用程序的设置信息 打开注册表的方式很简单:cmd中输入regedit 卸载路径只有一个 已安装32位的程序,如果是系统是32位...