Python 在问答频道中刷题积累到的小技巧(三)

x33g5p2x  于2022-06-08 转载在 Python  
字(6.0k)|赞(0)|评价(0)|浏览(555)

1. sum() 二维元组降维,本质就是多个元组也能相加。

  1. >>> tpl = ( (1,2,3),(1,2) )
  2. >>> sum(tpl,())
  3. (1, 2, 3, 1, 2)
  4. >>> sum(tpl,(0,))
  5. (0, 1, 2, 3, 1, 2)
  6. >>> tpl = ( (1,2,3),(4,5) )
  7. >>> sum(tpl,())
  8. (1, 2, 3, 4, 5)
  9. >>> sum(tpl,(0,)) # 单元素元组要加逗号:(0,),否则 (0)==0
  10. (0, 1, 2, 3, 4, 5)
  11. >>> (1,2,3)+(4,5)
  12. (1, 2, 3, 4, 5)
  13. >>> (0,)+(1,2,3)+(4,5)
  14. (0, 1, 2, 3, 4, 5)
  15. >>>

【实例】编写函数,接收数列,返回一个元组,其中第一个元素为所有参数的平均值,其他元素为所有参数中大于平均值的实数。

以下两个函数等价: 

  1. def func1(lst):
  2. t = sum(lst)/len(lst)
  3. return sum((tuple(i for i in lst if i>t),),(t,))
  4. def func2(lst):
  5. t = sum(lst)/len(lst)
  6. return (t,)+tuple(i for i in lst if i>t)

相关阅读:上期第2点列表降维:Python 在问答频道中刷题积累到的小技巧(二)_Hann Yang的博客-CSDN博客

2. '#'号输出日期短格式:'%Y-%#m-%#d' => '2022-6-6'。

附datetime.date常用属性及方法:

  1. >>> import datetime as dt
  2. >>> d = dt.date(2022,6,6)
  3. >>> d.year
  4. 2022
  5. >>> d.month
  6. 6
  7. >>> d.day
  8. 6
  9. >>> d.weekday()
  10. 0
  11. >>> d.isoweekday()
  12. 1
  13. >>> d.max
  14. datetime.date(9999, 12, 31)
  15. >>> d.min
  16. datetime.date(1, 1, 1)
  17. >>> d.ctime()
  18. 'Mon Jun 6 00:00:00 2022'
  19. >>> d.timetuple()
  20. time.struct_time(tm_year=2022, tm_mon=6, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=157, tm_isdst=-1)
  21. >>> d.strftime('%Y-%#m-%#d') #日期短格式
  22. '2022-6-6'
  23. >>> d.isoformat()
  24. '2022-06-06'
  25. >>> d.isocalendar()
  26. (2022, 23, 1) #当年第23周第1天
  27. >>> d.resolution
  28. datetime.timedelta(days=1)
  29. >>> d + dt.timedelta(2)
  30. datetime.date(2022, 6, 8)
  31. >>> d.toordinal()
  32. 738312
  33. >>> d-d.min
  34. datetime.timedelta(days=738311)
  35. >>> d - dt.timedelta(d.toordinal()-1)
  36. datetime.date(1, 1, 1)
  37. >>> d.max-d
  38. datetime.timedelta(days=2913747)
  39. >>> dt.date(2023,1,1)-d
  40. datetime.timedelta(days=209)
  41. datetime.date(2022, 6, 6)
  42. >>> d.replace(2023)
  43. datetime.date(2023, 6, 6)
  44. >>> d.replace(d.year,7)
  45. datetime.date(2022, 7, 6)
  46. >>> d.replace(d.year,d.month,8)
  47. datetime.date(2022, 6, 8)
  48. >>> d.replace(d.year,7,8)
  49. datetime.date(2022, 7, 8)
  50. >>> d.replace(2002,7,8)
  51. datetime.date(2002, 7, 8)
  52. >>> d
  53. datetime.date(2022, 6, 6) #d未变更

3. 列表指定位置插入、替换或删除元素:lst[m:m] = [x] 。

  1. >>> lst = [1,2,3,4,5]
  2. >>> lst
  3. [1, 2, 3, 4, 5]
  4. >>> lst[3:3] = [0]
  5. >>> lst
  6. [1, 2, 3, 0, 4, 5]
  7. >>> lst[3] = [0] # 对比
  8. >>> lst
  9. [1, 2, 3, [0], 4, 5]
  10. >>> lst[3:4] = [] # 删除索引为3的元素
  11. >>> lst
  12. [1, 2, 3, 4, 5]
  13. >>> lst[3:3] = [] # 这样lst没有变动
  14. >>> lst
  15. [1, 2, 3, 4, 5]
  16. >>> lst[3:3] = [6,7,8]
  17. >>> lst
  18. [1, 2, 3, 6, 7, 8, 4, 5]
  19. >>> lst[3:6] = [] # 恢复原状
  20. >>> lst
  21. [1, 2, 3, 4, 5]
  22. >>> lst[-1:] = [7,8,9] # 列表去尾相接
  23. >>> lst
  24. [1, 2, 3, 4, 7, 8, 9]
  25. >>> lst[4:] = [5] # 恢复原状
  26. >>> lst
  27. [1, 2, 3, 4, 5]
  28. >>> lst[1:4] = [0, 0, 0] # 替换
  29. >>> lst
  30. [1, 0, 0, 0, 5]
  31. >>> lst[2:3] = [1, 1] # 替换+插入
  32. >>> lst
  33. [1, 0, 1, 1, 0, 5]
  34. >>> lst.insert(3, 2) # 单个元素插入等价于 lst[3:3]=[2]
  35. >>> lst
  36. [1, 0, 1, 2, 1, 0, 5]
  37. >>>
  38. >>> lst = [*range(1,6)]
  39. >>> lst[-1:] = range(1,6)[::-1]
  40. >>> lst
  41. [1, 2, 3, 4, 5, 4, 3, 2, 1]
  42. >>> lst[:4] = [] # 删除前面的字符
  43. >>> lst
  44. [5, 4, 3, 2, 1]

4. 多项式求和时循环变量设置成题目中的一致,只要照抄。

例1: 2/(13) - 3/(25) + 4/(37) - 5/(49) + ... +  (-1)^(n-1) * (n+1) / [ n*(2*n+1) ]

  1. m = int(input())
  2. s = 0
  3. for n in range(1,m+1):
  4.     s += (-1)**(n-1) * (n+1) / ( n*(2*n+1) )
  5. print(round(s, 4))

例2: 1 - 1/2! + 1/4! - 1/6! + ... + (-1)^(n-1)/(2n-2)!

  1. m = int(input())
  2. res, t = 1.0, 1
  3. for n in range(1,m):
  4. t *= (2*n - 1) * n*2 //最后一项是(n-1),代入n*2即(2*n-2)
  5. res += (-1)**n/t
  6. print(res)

5. 任意多个递增序列合并一个递增序列(非相加后排序)。

  1. L0 = [3, 21, 24, 30, 36, 43, 46, 71, 82, 84, 96]
  2. L1 = [7, 15, 22, 23, 32, 39, 41, 51, 74, 76, 87, 89]
  3. L2 = [1, 18, 27, 31, 34, 35, 37, 48, 53, 57, 58, 81, 85, 97, 100]
  4. L = [list(i) for i in (L0, L1, L2)]
  5. res = []
  6. while sum(map(lambda x:len(x),L)):
  7. t, dic = [], {}
  8. for i in range(len(L)):
  9. if L[i]:
  10. dic[L[i][0]] = i
  11. t.append(L[i][0])
  12. res.append(min(t))
  13. L[dic[min(t)]][:1] = []
  14. print(res)

附录:

Help on class date in module datetime:

class date(builtins.object)
 |  date(year, month, day) --> date object
 |  
 |  Methods defined here:
 |  
 |  add(self, value, /)
 |      Return self+value.
 |  
 |  eq(self, value, /)
 |      Return self==value.
 |  
 |  format(...)
 |      Formats self with strftime.
 |  
 |  ge(self, value, /)
 |      Return self>=value.
 |  
 |  getattribute(self, name, /)
 |      Return getattr(self, name).
 |  
 |  gt(self, value, /)
 |      Return self>value.
 |  
 |  hash(self, /)
 |      Return hash(self).
 |  
 |  le(self, value, /)
 |      Return self<=value.
 |  
 |  lt(self, value, /)
 |      Return self<value.
 |  
 |  ne(self, value, /)
 |      Return self!=value.
 |  
 |  radd(self, value, /)
 |      Return value+self.
 |  
 |  reduce(...)
 |      reduce() -> (cls, state)
 |  
 |  repr(self, /)
 |      Return repr(self).
 |  
 |  rsub(self, value, /)
 |      Return value-self.
 |  
 |  str(self, /)
 |      Return str(self).
 |  
 |  sub(self, value, /)
 |      Return self-value.
 |  
 |  ctime(...)
 |      Return ctime() style string.
 |  
 |  isocalendar(...)
 |      Return a 3-tuple containing ISO year, week number, and weekday.
 |  
 |  isoformat(...)
 |      Return string in ISO 8601 format, YYYY-MM-DD.
 |  
 |  isoweekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 1 ... Sunday == 7
 |  
 |  replace(...)
 |      Return date with new specified fields.
 |  
 |  strftime(...)
 |      format -> strftime() style string.
 |  
 |  timetuple(...)
 |      Return time tuple, compatible with time.localtime().
 |  
 |  toordinal(...)
 |      Return proleptic Gregorian ordinal.  January 1 of year 1 is day 1.
 |  
 |  weekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 0 ... Sunday == 6
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  fromisocalendar(...) from builtins.type
 |      int, int, int -> Construct a date from the ISO year, week number and weekday.
 |      
 |      This is the inverse of the date.isocalendar() function
 |  
 |  fromisoformat(...) from builtins.type
 |      str -> Construct a date from the output of date.isoformat()
 |  
 |  fromordinal(...) from builtins.type
 |      int -> date corresponding to a proleptic Gregorian ordinal.
 |  
 |  fromtimestamp(timestamp, /) from builtins.type
 |      Create a date from a POSIX timestamp.
 |      
 |      The timestamp is a number, e.g. created via time.time(), that is interpreted
 |      as local time.
 |  
 |  today(...) from builtins.type
 |      Current date or datetime:  same as self.class.fromtimestamp(time.time()).
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  new(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  day
 |  
 |  month
 |  
 |  year
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  max = datetime.date(9999, 12, 31)
 |  
 |  min = datetime.date(1, 1, 1)
 |  
 |  resolution = datetime.timedelta(days=1)

相关文章