简单的选择排序
lst1 = [8,2,4,5,6,3,1,9,7]
length = len(lst1)
for i in range(length):
maxindex = i
for j in range(i+1,length):
if lst1[maxindex] < lst1[j]:
maxindex = j
if i != maxindex:
tmp = lst1[i]
lst1[i] = lst1[maxindex]
lst1[maxindex] = tmp
print(lst1)
输入一个数字,打印每一位数字及其重复的次数
num = input(“>”)
d = {}
for c in num:
if not d.get(c):
d[c] = 1
continue
d[c] += 1
print(d)
方法二:
num = input(“>”)
d = {}
for c in num:
if c not in d.keys():
d[c] = 1
else:
d[c] += 1
print(d)
数字重复统计
import random
n = 100
nums = [0] * n
for i in range(n):
nums[i] = random.randint(-1000,1000)
# print(nums)
t = nums.copy()
t.sort()
print(t)
b = len(t)
方法二:
import random
n = 100
nums = [0] * n
for i in range(n):
nums[i] = random.randint(-1000,1000)
d = {}
for x in nums:
if x not in d.keys():
d[x] = 1
else:
d[x] += 1
print(d)
d1 = sorted(d.items())
print(d1)
字符串重复统计:
import random
alphabet = ‘ffjdkhfjkdshfjdkshfjdkshfjkdbghfdffweferyeuwioqifj’
words = []
for _ in range(100):
words.append(random.choice(alphabet)+random.choice(alphabet))
# print(words)
d = {}
for x in words:
d[x] = d.get(x,0) + 1
print(d)
d2 = sorted(d.items())
print(d2)
列表解析习题:
1-10 平方的列表
[ x**2 for x in range(10)]
求一个列表相邻两个相加的和
lst = [1,4,9,16,2,5,10,15]
[lst[i]+lst[i+1] for i in range(len(lst)-1)]
列表解析打印救救乘法表
[print(‘{}*{}={:<3}{}’.format(j,i,i*j,’\n’ if i==j else ”),end=”) for i in range(1,10) for j in range(1,i+1)]
生成 ID
方法一:
import random
[‘{:04}.{}’.format(n, ”.join([random.choice(bytes(range(97,123)).decode()) for _ in range(10)])) for n in range(1,101)]
方法二:
import random
[‘{:04}.{}’.format(i,”.join([chr(random.randint(97,122)) for j in range(10)])) for i in range(1,101)]
方法三:
import string
[‘{:>04}.{}’.format(i, ”.join(random.choice(string.ascii_lowercase) for _ in range(0,10))) for i in range(1,101)]
本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/87769