Python数据结构基础(一)——列表(List)

版权声明:本文版权归作者所有,未经允许不得转载! https://blog.csdn.net/m0_37827994/article/details/86490764

二、列表

列表是Python中的对象,可以保存数字和文本的有序序列

  • 列表(list)要用 [ ] 来装数字
  • 列表(list)中的内容可改变

1、创建一个列表

# Creating a list
list_x = [3, "hello", 1]
print (list_x)

输出结果:

[3, 'hello', 1]

2、添加一个列表

# Adding to a list
list_x.append(7)
print (list_x)

输出结果:

[3, 'hello', 1, 7]

3、访问列表中特定位置的项

# Accessing items at specific location in a list
print ("list_x[0]: ", list_x[0])
print ("list_x[1]: ", list_x[1])
print ("list_x[2]: ", list_x[2])
print ("list_x[-1]: ", list_x[-1]) # the last item
print ("list_x[-2]: ", list_x[-2]) # the second to last item

输出结果:

list_x[0]:  3
list_x[1]:  hello
list_x[2]:  1
list_x[-1]:  7
list_x[-2]:  1
  • 注:这里再声明一下,[-1]是列表中的导数第一个数;[-2]是列表中的导数第二个数。

4、Slicing

# Slicing
print ("list_x[:]: ", list_x[:])
print ("list_x[2:]: ", list_x[2:])
print ("list_x[1:3]: ", list_x[1:3])
print ("list_x[:-1]: ", list_x[:-1])

输出结果:

list_x[:]:  [3, 'hello', 1, 7]
list_x[2:]:  [1, 7]
list_x[1:3]:  ['hello', 1]
list_x[:-1]:  [3, 'hello', 1]

5、列表的长度

# Length of a list
len(list_x)

输出结果:

4

6、替换列表中的某一项

# Replacing items in a list
list_x[1] = "hi"
print (list_x)

输出结果:

[3, 'hi', 1, 7]

7、合并列表

# Combining lists
list_y = [2.4, "world"]
list_z = list_x + list_y
print (list_z)

输出结果:

[3, 'hi', 1, 7, 2.4, 'world']

猜你喜欢

转载自blog.csdn.net/m0_37827994/article/details/86490764