本文共 2712 字,大约阅读时间需要 9 分钟。
def RandomNumber(length, num): tmp = [i + 1 for i in range(num)] random.shuffle(tmp) i = 0 list1 = [] while i < length: list1.append(tmp[i]) i = i + 1 list1.sort() print(list1)RandomNumber(5, 35)RandomNumber(2, 12)
运行结果:
"F:\Python 3.8.0\python.exe"[4, 6, 9, 21, 22][1, 10]进程已结束,退出代码 0
1. 赋值其实只是传递对象引用,引用对象id是一样的。2. 浅拷贝是指拷贝的只是原始对象元素的引用,换句话说,浅拷贝产生的对象本身是新的,但是它的内容不是新的,只是对原对象的一个引用。3. 深拷贝是指完全拷贝原始对象,而且产生的对象是新的,并且不受其他引用对象的操作影响。
from copy import copy, deepcopya = [1,2,3,['a','b','c']]b = a #都不是新的c = copy(a) #内容不是新的d = deepcopy(a) #都是新的print(a)print(b)print(c)print(d)#用is 判断两个标识符是不是引用自一个对象if (a is b): print("1 - a 和 b 有相同的标识")else: print("1 - a 和 b 没有相同的标识")if (a is c): print("3 - a 和 c 有相同的标识")else: print("3 - a 和 c 没有相同的标识")if (a is d): print("5 - a 和 d 有相同的标识")else: print("5 - a 和 d 没有相同的标识")a.append(9)#在a中添加个9a[3].append('d')#在a中添加个dprint(a)print(b)print(c)print(d)
运行结果:
"F:\Python 3.8.0\python.exe" [1, 2, 3, ['a', 'b', 'c']][1, 2, 3, ['a', 'b', 'c']][1, 2, 3, ['a', 'b', 'c']][1, 2, 3, ['a', 'b', 'c']]1 - a 和 b 有相同的标识3 - a 和 c 没有相同的标识5 - a 和 d 没有相同的标识[1, 2, 3, ['a', 'b', 'c', 'd'], 9][1, 2, 3, ['a', 'b', 'c', 'd'], 9][1, 2, 3, ['a', 'b', 'c', 'd']][1, 2, 3, ['a', 'b', 'c']]进程已结束,退出代码 0
例如:arr = [1,2,3,4,5,6] 将长度为6的数组arr的前面2个元素 翻转到数组尾部。 得到: arr = [3,4,5,6,1,2]
def rverse(arr, start, end): while (start < end): temp = arr[start] # temp=1 arr[start] = arr[end] # arr[start]=2 arr[end] = temp # arr[end]=1 start += 1 end = end - 1def exchange(arr, sub): n = len(arr)-1 rverse(arr,0,sub-1)#把前面sub个交换顺序 rverse(arr,sub,n)#把后面n-sub个交换顺序 rverse(arr,0,n)#所有的交换顺序arr = [1, 2, 3, 4, 5, 6]exchange(arr, 2)print(arr)
运行结果:
"F:\Python 3.8.0\python.exe"[3, 4, 5, 6, 1, 2]进程已结束,退出代码 0
str="Man is the master of his destiny."if "is" in str: print("is存在")else: print("is不存在")if str.find("word") >=0: print("word存在")else: print("word不存在")
运行结果:
"F:\Python 3.8.0\python.exe" is存在word不存在进程已结束,退出代码 0
def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return Falsemy_dictionary= { 'data1': 10, 'data2': -5, 'data3': 2,'data4':"adda",}result = 1for key in my_dictionary: if is_number(my_dictionary[key]) is True: #判断是否为数字 result = result * my_dictionary[key]print(result)
运行结果:
"F:\Python 3.8.0\python.exe" -100进程已结束,退出代码 0
转载地址:http://zzywi.baihongyu.com/