跳至主要内容

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)

评论

此博客中的热门博文

Mongo 入门

https://pymongo.readthedocs.io/en/stable/tutorial.html https://www.mongodb.com/languages/python https://zhuanlan.zhihu.com/p/51171906 https://www.runoob.com/python3/python-mongodb.html https://blog.baoshuo.ren/post/luogu-spider/ https://hub.docker.com/_/mongo 安装 MongoDB $ docker search mongo 启动一个mongo服务器实例 $ docker run --name some-mongo -d mongo:tag some-mongo是您要分配给容器的名称,tag是指定您想要的 MongoDB 版本的标签 MongoDB 的默认数据目录路径是/data/db 如下: $ docker run -it -v mongodata:/data/db -p 27017:27017 --name mongodb --restart unless-stopped -d mongo 你应该让 MongoDB 在端口 27017 上运行,并且可以通过localhostWindows 和 Ubuntu 20.04 上的URL访问 http://localhost:27017/ -p 是 HOST_PORT:CLIENT_PORT  -P 随机端口 -p 27017:27017 :将容器的27017 端口映射到主机的27017 端口 -v mongodata:/data/db :将主机中当前目录下的db挂载到容器的/data/db,作为mongo数据存储目录 从另一个 Docker 容器连接到 MongoDB 镜像中的 MongoDB 服务器侦听标准 MongoDB 端口27017,因此通过 Docker 网络连接将与连接到远程mongod. 以下示例启动另一个 MongoDB 容器实例,并mongo针对上述示例中的原始 MongoDB 容器运行命令行客户端,从而允许您针对数据库实例执行 MongoDB 语句: $ docker run -it --network some-network --...

端口映射 公网访问内网

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

安装和卸载软件(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位...