软件测试软件测试test

Python基础篇(一)

2018-10-10  本文已影响14人  会飞的小马

python基础方法与函数

以上几个方法并不会改变列表实际的值

name = "Ada Lovelace"
print(name.title())
print(name.upper())
print(name.lower())
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
输出:
['ducati', 'honda', 'yamaha', 'suzuki']
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop(2)
print(motorcycles)
print(popped_motorcycle)
print(popped_motorcycle[1])
输出:
['honda', 'yamaha']
suzuki
u
motorcycles.append('元素')
motorcycles.insert(2,'元素')
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
too_expensive = 'ducati'  #先给删除的值定义变量
motorcycles.remove(too_expensive) #通过变量删除该列表中的值
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")#通过变量中的存储使用已删除的值

注意使用remove只能删除列表只有唯一的这一个值,如值有多个需使用循环

一般来说对数据有永久性改变的方法不可直接print,需先处理数据赋予变量

for value in range(1,4):
print(value)
输出:
1
2
3    #会比指定的差1
numbers = list(range(1,6))
print(numbers)
输出:
[1, 2, 3, 4, 5]

range()函数可指定步长

例如:

numbers = list(range(2,11,2))#从2开始,步长为2
print(numbers)
输出:
[2, 4, 6, 8, 10]

range()函数可创建运算后的数字集合如开平方

例如:

aa = []
for value in range(1,11):
  aa.append(value**2)
print(aa)
输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表解析将for 循环和创建新元素的代码合并成一行,并自动附加新元素
例如:

aa = [value**2 for value in range(1,11)]
print(aa)
输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
name = ['a','b','c','d','e']
print (name[1:3])
输出
['b','c']
print (name[-2:])
输出
['d','e']
>>> 4 % 3
1
 >>> 5%3
2
 >>> 6%3
0 
>>
上一篇 下一篇

猜你喜欢

热点阅读