python位置索引方法s.index(x[、m[、n)_知识分享!Python3
Python3使用积累
最近可能要经常使用Python,所以记录一下Python的相关用法。
算法竞赛中的积累
头写法
if __name__ == '__main__':
1
初始化\输入
1.读取一维数组
arr = list(map(int, input().split(' ')))
2.初始化全0的二维数组
st = [[0 for col in range(n)] for row in range(m)]
3.读入n,m
n, m = map(int, input().split(' '))
输出
1.输出一维数组的值
print(' '.join(map(str, arr)))
2.输出float,保留小数点后6位,
冒号后接整数表述输出宽度,点后面加6表示保留小数点后6位
print('{:.6f}'.format(n))
字符串
1.判断某个字符串前缀,例如"I love you"中的单词,
是否有"yo"这个前缀,有则输出下标(3),否则输出-1
for i, s enumerate(str.split()):
if (s.startswith("yo")) return i + 1
return -1
其他技巧
1.交换数组第i位和第j位的值
arr[i], arr[j] = arr[j], arr[i]
2.三目运算符
st = 1 if n < 0 else 0
3.函数中使用全局变量,记得声明 global,避免混淆
数组
1.数组常用方法
len(list) 返回数组长度
max(list) 返回数组最大的数
list.append(obj) 向数组插入一个对象
list.count(obj) 统计数组某个对象的个数
list.index(obj) 返回某个对象的索引
list.inser(index, obj) 在某个位置插入对象
list.pop(index=-1) 弹出某个index下标的数,默认最后一个元素,并返回该值
list.remove(obj) 移除列表中某个对象的第一个匹配项
list.reverse() 翻转
list.sort(key=None, reverse=False) 排序
数据科学中的使用
字典
1.增:update可以批量添加
dic.update({'name': 'zouyuhang', 'sex': 'man'})
2.删:del,pop
del dic['sex']
dic.pop('sex')
3.查:get, 当查询的key不存在的时候,返回默认值
dic.get('sex', 0)
4.改:
dic['name'] = 'tom'
5.遍历
for key, value in dic.items():
print(key, value)
函数
1.任意参数
def func(*name):
...
元组
animals = ('souge', 'lama')
1.index索引
animals = ('souge', 'lama')
print(animals.index('lama')) # 1
2.count计数
print(animals.count('lama')) # 1
3.元组拆包
x, y = (7, 10);
a, b, *c = (1, 2, 3, 4, 5)
print("Value of x is {}, the value of y is {}.".format(x, y))
4.枚举
friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, friend in enumerate(friends):
print(index,friend)
Python随机数
# 1.random()方法即可随机生成一个[0,1)范围内的实数
import random
ran = random.random()
print(ran) #0.7948628379323708
# 2.预先使用 random.seed(x) 设定好种子之后,
# 其中的 x 可以是任意数字,
# 此时使用 random() 生成的随机数将会是同一个。
print ("------- 设置种子 seed -------")
random.seed(10)
print ("Random number with seed 10 : ", random.random())
#
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
