lists-列表操作
列表索引的某个项目可以重新赋值
举例:
nums = [8, 8, 8, 8]
nums[3] =6
print(nums)
Result:
>>>
[8, 8, 8, 6]
>>>
填空 创建一个列表list, 重新赋值第二个元素并打印
nums = [34, 45, 65]
nums[1] = 22
print(nums)
[34, 22, 65]
list-列表乘&加
列表list 可以添加也可以相乘,字符串也一样
举个栗子:
nums = [2, 2, 4]
print(nums + [2, 3, 4])
print(nums * 2)
结果:
>>>
[2, 2, 4, 2, 3, 4]
[2, 2, 4,2, 2, 4 ]
>>>
列表和字符串在很多方面都是相似的——字符串可以被看作是无法更改的字符列表
List-检测-in
用in语句来检查列表中是否有某个项目,如果返回 True 则有,返回False则没有
words = ["spam", "egg", "spam", "sausage"]
print("spam" in words)
print("egg" in words)
print("tomato" in words)
结果:
>>>
True
True
False
>>>
in运算符还用于确定字符串是否是另一个字符串的子字符串。
填空 这段代码的运行结果是多少?
nums = [10, 9, 8, 7, 6, 5]
nums[0] = nums[1] - 5
if 4 in nums:
print(nums[3])
else:
print(nums[4])
7
如果列表中包含z打印Yes
letters = ["a", "b", "z"]
lf "z" in letters:
print("Yes")
List-检测-not
not语句可以检查某个元素不在列表里。如下:
nums = [1, 2, 3]
print(not 4 in nums)
print(4 not in nums)
print(not 3 in nums)
print(3 not in nums)
结果:
>>>
True
True
False
False
>>>
List-函数-append,更改列表的另一种方法是使用append方法。在列表的最后面添加一项。
numsa = [4,5,6]
numsa.append(5)
print(numsa)
结果:
>>>
[4,5,6,5]
>>>
List-函数-len,len方法用来查看列表中项目的个数
numsa = [3, 5, 7, 9, 11,13]
print(len(numsa))
结果:
>>>
6
>>>
List-函数-insert,insert 方法比较像 append,它允许你在列表中的任何位置插入一个新的项目,而不是只在最后一个位置
word = ["Python", "fun"]
one= 1
words.insert(one, "is")
print(word)
结果:
>>>
['Python', 'is', 'fun']
>>>
List-函数-index,index方法查找列表 第一个出现的项目并返回其索引。
如果项不在列表中,则会引发ValueError。
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.index('r'))
print(letters.index('p'))
print(letters.index('z'))
结果:
>>>
2
0
ValueError: 'z' is not in list
>>>
这里有一些关于列表list有用的方法,max(list): 返回列表中最大的值,min(list): R返回列表中最小的值,list.count(obj): 返回一个项目在列表中出现的次数,list.remove(obj): 从列表中删除一个项目,list.reverse(): 翻转列表中的项目
Range函数
range 函数 创建一个 有序的数字列表,
生成一个0到9的整数列表:
numbers = list(range(10))
print(numbers)
结果:
>>>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
列表的调用是必需的,因为range本身创建了一个范围对象,如果您想将它作为一个对象,则必须将其转换为列表。
如果range只有一个参数,它将产生一个0到参数的列表,如果range有两个参数,它将产生一个从一个参数到第二个参数的值的列表
例如:
numbers = list(range(2, 7))
print(numbers)
print(range(20) == range(0, 20))
结果:
>>>
[2, 3 4, 5, 6]
True
Range-参数3个,range 也可以有第三个参数, 它决定所产生的序列的间隔。这第三个参数必须是整数。
numbers = list(range(5, 20, 2))
print(numbers)
结果是:
>>>
[5, 7, 9, 11, 13, 15, 17, 19]
关注公众号,每天可以领红包