python中的List/列表的相关操作

列表/List

一: 列表(List)的基本概念

  • 列表是 python 的一种数据类型,功能上比较像matlab里面的cell类型,一个可以存放各种数据类型的’数组。
  • string 可以当做一个 list 对象进行索引。

For example

#example 1 列表的定义
number = 3
things = ["string", 0, [1, 2, number], 4.56]
print(things[1])
print(things[2])
print(things[2][2])

#example 2  string当做列表索引
str = "Hello world!"
print(str[6])

Result

#example 1
0
[1, 2, 3]
3

#example 2
w

二: 列表的操作(List Operations)

  • 列表元素的赋值/输出
  • 列表相加(拼接)
  • 列表乘以整数,类似string,自我复制。
  • 查看列表中是否有指定元素。
  • 截取List中的slice, 包前不包后

For example

#example 1 列表相加/拼接
nums = [1, 2, 3] 
print(nums + [4, 5, 6])
#result-----------
#[1, 2, 3, 4, 5, 6]


#example 2 列表乘以整数, 列表自我复制
print(nums*3)
#result-----------
#[1, 2, 3, 1, 2, 3, 1, 2, 3]

#example 3 查看是否有指定元素
words = ["spam", "egg", "spam","sausage"]
print("spam" in words)
print(not "tomato" in words)
#result-----------
#True
#True

#example 4 选取List的片段, 包前不包后
letters = ['a', 'b', 'c', 'd', 'e']
slice = letters[1:3]
print slice
#result-----------
#'b', 'c']
#examples 5 若索引从头开始或者到最后一个元素,
#可省略第一个或者最后一个元素的索引

animals = "catdogfrog"

# The first three characters of animals
cat = animals[:3]

# The fourth through sixth characters
dog = animals[3:6]

# From the seventh character to the end
frog = animals[6:]

三 列表常用函数(List Functions)

  • 后接元素: 添加某一项 List.append()
  • 查找指定元素的索引: 查找列表中指定项字符’b’的索引 list.index(‘b’),若没此项则报错。
  • 插入元素: 在列表指定位置idx添加元素a List.insert(idx, a)(原先idx位置的元素及其后面的元素会自动后移) ;
  • 删除元素: 删除LIst中的某一项,函数List.remove(), 括号中填写要删除的内容
  • List各元素中插入元素: “string”.join(List)

example: 查索引( .index ),插元素( .insert() )示例


animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]

# Use index() to find "duck"
duck_index = animals.index("duck")

# Use the index to insert the string "cobra"
animals.insert(duck_index, "cobra")

print animals 
#result ----------------
#['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox']

example 各元素中间插入新元素( .join() )

letters = ['a', 'b', 'c', 'd']
print " ".join(letters)
print "---".join(letters)

#result
#a b c d
#a---b---c---d

四 for循环遍历List的两中方案

Method 1 - for item in list:

for item in list:
  print item

Method 2 - iterate through indexes:

for i in range(len(list)):
  print list[i]

二者优缺点:
Method 1 用起来方便, 但是无法修改List内容
Method 2 通过索引来遍历List中的内容,虽然用起来麻烦,但是可以对List中的内容进行修改

猜你喜欢

转载自blog.csdn.net/qq_29007291/article/details/79187079