Python世界:高频小技巧总结

发布于:2025-02-11 ⋅ 阅读:(126) ⋅ 点赞:(0)

iPython清屏指令?

  • !CLS, Clear Screen

类型转换技巧总结?

  • multi_res_str = "".join(multi_res_list) # 列表转字符串
  • int(str),字符串到整数
  • float(str),字符串浮点
  • str(num),数到字符串
  • // 实现整除
  • % 实现取余

万能的排序函数汇总?

列表排序

sorted(list1,reverse=True)

字典排序

dic2asc=sorted(dic1,key=dic1.__getitem__)

dic4asc=sorted(dic1.items(),key=lambda dic1:dic1[1])

d = {'mike': 10, 'lucy': 2, 'ben': 30}

# 根据字典值的升序排序

d_sorted_by_value = sorted(d.items(), key=lambda x: x[1]) # 若元素为数值,在x[1]前添加负号也可,降序排序

print(d_sorted_by_value)

# 根据字典值的降序排序

d_sorted_by_value = sorted(d.items(), key=lambda x: x[1], reverse=True) # 默认按升序排,reverse入参默认是False,如果要降序,则reverse=True

print(d_sorted_by_value)

# 根据字典键的升序排序

d_sorted_by_value = sorted(d.items(), key=lambda x: x[0])

print(d_sorted_by_value)

# 根据字典键的降序排序

d_sorted_by_value = sorted(d.items(), key=lambda x: x[0], reverse=True)

print(d_sorted_by_value)

如何1条指令快速生成二维数组?

  • res = [[0]*res_len for i in range(res_len)] # list迭代生成二维数组

如何高效遍历数组及索引?

在for循环中,如果需要同时访问索引和元素,你可以使用enumerate()函数来简化代码。

l = [1, 2, 3, 4, 5, 6, 7]
# 获取列表元素值及对应索引
for index, item in enumerate(l):
  if index < 5:
    print(item) 

高频高效的小函数有哪些?

  • map/range,函数是用c写的,效率最高
  • filter,根据条件过滤取值
  • map,根据表达式对原数据做映射变换
  • reduce,累乘元素
  • sum,累加元素

列表生成有哪些简洁写法?

expression1 if condition else expression2 for item in iterable
expression for item in iterable if condition

text = ' Today, is, Sunday'
text_list = [s.strip() for s in text.split(',') if len(s.strip()) > 3]
print(text_list)
# ['Today', 'Sunday']

# 法1
l = []
for xx in x:
  for yy in y:
     if xx != yy:
     	l.append((xx, yy))

# 法2
l2 = [(xx, yy) for xx in x for yy in y if xx != yy]

如何通过Python脚本打开运行exe,并传参?

# r_v = os.system(para)
# print(r_v) # 仅能返回main值

r = os.popen(para) # 可以获取stdout打印的结果
text = r.read()
r.close()
print(text)

网站公告

今日签到

点亮在社区的每一天
去签到