Python学习第四天

列表

列表的创建:

  1. 使用中括号[]
list = ['hello', 'world', 123, 3.14]
print(list)

####
['hello', 'world', 123, 3.14]
  1. 使用函数list()
    函数中的参数必须是可迭代对象
list1 = list(range(3))
list2 = list(['hello', 1, 3.1])
print(list1)
print(list2)

####
[0, 1, 2]
['hello', 1, 3.1]

获取指定元素的索引

使用index([value])方法
如果列表中存在相同元素,只返回第一个元素的索引

l = ['hello', 'xyq', 123, 'hello']
print(l.index(123))
print(l.index('xyq'))
print(l.index(123, 1, 3))  #在[start,stop)之间查找元素value
print(l.index('x'))


####
2
1
2
Traceback (most recent call last):
  File "/Users/xieyuquan/PycharmProjects/LearnPython/main.py", line 4, in <module>
    print(l.index('x'))
ValueError: 'x' is not in list

获取单个元素

正向索引:0~N-1
负向索引:-1~-N

l = ['hello', 'xyq', 123, 'hello']
print(l[0])
print(l[-4])

####
hello
hello

获取多个元素

列表[start : stop : step]

l = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print(l[1:4])
print(l[1:5:2])
print(l[:5])
print(l[::])
print(l[0::])

print(l[::-1])
print(l[:-5:-1])
print(l[:-6:-2])
####
[20, 30, 40]
[20, 40]
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
[100, 90, 80, 70]
[100, 80, 60]

判断元素在列表

使用innot in

l = [10, 20, 'xyq', 'p']
print(10 in l)
print(30 in l)
print('x' not in l)
print('xq' in l)


####
True
False
True
False

遍历列表

可以使用for-in

l = [10, 20, 'xyq', 'p']

for item in l:
    print(item, end=' ')

####
10 20 xyq p 

增加元素

l = [10, 20, 'xyq', 'p']

l.append(30)
l.append('x')
print(l)

l.extend(['s', 'h', 'y'])
print(l)
l.extend(range(2))
print(l)

l.insert(0, 1)
print(l)
l.insert(3, 30)
print(l)

l.append(l[4:8:])
print(l)

####
[10, 20, 'xyq', 'p', 30, 'x']
[10, 20, 'xyq', 'p', 30, 'x', 's', 'h', 'y']
[10, 20, 'xyq', 'p', 30, 'x', 's', 'h', 'y', 0, 1]
[1, 10, 20, 'xyq', 'p', 30, 'x', 's', 'h', 'y', 0, 1]
[1, 10, 20, 30, 'xyq', 'p', 30, 'x', 's', 'h', 'y', 0, 1]
[1, [123, 456], 10, 20, 30, 'xyq', 'p', 30, 'x', 's', 'h', 'y', 0, 1]
[1, [123, 456], 10, 20, 30, 'xyq', 'p', 30, 'x', 's', 'h', 'y', 0, 1, [30, 'xyq', 'p', 30]]

列表的删除操作

l = [10, 20, 'xyq', 'p', 10]

# l.remove(10)
# print(l)      #### [20, 'xyq', 'p', 10]

# l.pop()
# print(l)     #### [10, 20, 'xyq', 'p']

# l.pop(1)
# print(l)    #### [10, 'xyq', 'p', 10]


posted @ 2021-01-30 20:38  sxhyyq  阅读(43)  评论(0编辑  收藏  举报