本期干货满满,点赞收藏,以免下次找不到
输出对应顺序的索引
a = [5, 7, 2, 4, 3]
index = list(range(len(a)))
index.sort(key=lambda i: a[i]) # 从大到小只需要添加 负号就行 (key=lambda i: -a[i])
print("从小到大对应的索引:", index)
## 从小到大对应的索引: [2, 4, 3, 0, 1]
想打印字符串 “123” 但是 print 只输出 123
a = "123"
print(a)
## 123
只需要灵活运用单引号双引号,在外层嵌套单引号就可以啦
a = '"123"'
print(a)
## "123"
a = {"jack": 20, "jerry": 19, "babo": 24}
b = {value: key for key, value in a.items()}
print(b)
## {20: 'jack', 19: 'jerry', 24: 'babo'}
利用 colletions 库,经常会用到
from collections import Counter
a = [1, 1, 1, 2, 2, 3, 4, 5]
print(Counter(a))
## Counter({1: 3, 2: 2, 3: 1, 4: 1, 5: 1})
当然字符串也可以用
from collections import Counter
a = "fasdfasdfwqgsdgjh"
print(Counter(a))
## Counter({'f': 3, 's': 3, 'd': 3, 'a': 2, 'g': 2, 'w': 1, 'q': 1, 'j': 1, 'h': 1
字符串转列表
a = "a,b,c"
b = a.split(",")
print(b)
## ['a', 'b', 'c']
列表转字符串
a = ['a', 'b', 'c']
b = ''.join(a)
print(b)
## abc
a = "123456789"
print(a[::-1])
## 987654321
b = [1, 2, 3, 4, 5]
print(b[::-1])
## [5, 4, 3, 2, 1]
判断字符串是否为回文字符串
a = 1234321
b = str(a)
if b == b[::-1]:
print(True)
## True
利用集合的唯一性。
a = "asdfasdfasdfasd"
b = set(a)
print(b)
##{'s', 'f', 'a', 'd'}
判断元素是否有重复
a = 12344
b = None
if len(str(a)) == len(set(str(a))):
b = True
else:
b = False
print(b)
## False
字符串可以利用乘法 不要傻傻的 print (“**************************************”)
for i in range(2):
print("*" * 20)
print("name:", "jack")
print("age", 22)
## ********************
## name: jack
## age 22
## ********************
## name: jack
## age 22
每次随机取出一人,随机排序。每次运行结果都是随机的
import random
a = ["name1", "name2", "name3", "name4", "name5"]
while a:
b = random.randint(0, len(a) - 1)
print(a[b])
del a[b]
## name4
## name5
## name3
## name1
## name2
如果想要内定,就设定一个特定的种子,那顺序就是一定的。(种子默认随着时间改变而改变) 此时每次运行结果是一致的
import random
random.seed(1)
a = ["name1", "name2", "name3", "name4", "name5"]
while a:
b = random.randint(0, len(a) - 1)
print(a[b])
del a[b]
## name2
## name1
## name4
## name3
## name5