python学习-17 列表list 2

2019-07-24 09:07:39来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

# 1. 选择嵌套列表里的元素(内部进行了for循环)


li = [1,2,"age",["熊红","你好",["12",45]],"abc",True] a = li[3][2][1] print(a)

运行结果:

45

Process finished with exit code 0

#2. 字符串转换列表

a = "iamchinese"
b =list(a)
print(b)

运行结果:

['i', 'a', 'm', 'c', 'h', 'i', 'n', 'e', 's', 'e']

Process finished with exit code 0

#3. 列表转换字符串

第一种方法:(for循环)

li =[123,456,"abcdefg"]
b = " "
for a in li:
   b=b+str(a)
print(b)

运算结果:

123456abcdefg

Process finished with exit code 0

第二种方法:(列表中的元素只有字符串时)

li =["abcdefg"]
a ="".join(li)
print(a)

运行结果:

abcdefg

Process finished with exit code 0

#4. list 的其他功能

 

-追加(也可以加字符串,列表等)

li = [123,13121,55]
li.append(6)
print(li)

运算结果:

[123, 13121, 55, 6]

Process finished with exit code 0

 

 

-清空

li = [123,13121,55]
li.clear()
print(li)

运算结果:

[]

Process finished with exit code 0

 

 

-浅拷贝

li = [123,13121,55]
a = li.copy()
print(li)
print(a)

运算结果:

[123, 13121, 55]
[123, 13121, 55]

Process finished with exit code 0

 

 

-计数

li = [55,123,13121,55]
a =li.count(55)         #计算 55 出现过几次

print(a)

运算结果:

2

Process finished with exit code 0

 

-迭加

li = [1,2,3,4,5]
li.extend([7,8,9,"你好"])

print(li)

运算结果:

[1, 2, 3, 4, 5, 7, 8, 9, '你好']

Process finished with exit code 0

ps: append 将整个元素添加, extend 是内部经过for循环将一个添加

 

-获取位置

li = [1,22,33,4,5,33]
a
=li.index(33) #(从左向右获取索引位置(获取到第一个就不会继续了),可以指定位置li.index(0:3)) print(a)

运算结果:

2           #(索引,不是数量)

Process finished with exit code 0

 

-删除某个元素并获取删除的元素

li = [1,22,33,4,5,33]
a=li.pop()             #  可以指定索引位置(不指定索引,默认删除最后一个)
print(li)
print(a)

运算结果:

[1, 22, 33, 4, 5]
33

Process finished with exit code 0

 

-删除指定元素

li = [1,22,33,4,5,33]
li.remove(33)    #从左向右只删除第一个
print(li)

运算结果:

[1, 22, 4, 5, 33]

Process finished with exit code 0

 

-反转

li = [1,22,33,4,5,33]
li.reverse()
print(li)

运算结果:

[33, 5, 4, 33, 22, 1]

Process finished with exit code 0

 

-排序

li = [1,22,33,4,5,33]
li.sort(reverse=True)        # 括号里不填默认从小到大排序
print(li)

运算结果:

[33, 33, 22, 5, 4, 1]

Process finished with exit code 0

 


原文链接:https://www.cnblogs.com/liujinjing521/p/11102598.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:多线性方程组迭代算法——Jacobi迭代算法的Python实现

下一篇:针对源代码和检查元素不一致的网页爬虫——利用Selenium、Phanto