热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

1.sum

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

>>> tpl = ( (1,2,3),(1,2) )
>>> sum(tpl,())
(1, 2, 3, 1, 2)
>>> sum(tpl,(0,))
(0, 1, 2, 3, 1, 2)
>>> tpl = ( (1,2,3),(4,5) )
>>> sum(tpl,())
(1, 2, 3, 4, 5)
>>> sum(tpl,(0,)) # 单元素元组要加逗号:(0,),否则 (0)==0
(0, 1, 2, 3, 4, 5)
>>> (1,2,3)+(4,5)
(1, 2, 3, 4, 5)
>>> (0,)+(1,2,3)+(4,5)
(0, 1, 2, 3, 4, 5)
>>>

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

以下两个函数等价: 

def func1(lst):
t = sum(lst)/len(lst)
return sum((tuple(i for i in lst if i>t),),(t,))
def func2(lst):
t = sum(lst)/len(lst)
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常用属性及方法:

>>> import datetime as dt
>>> d = dt.date(2022,6,6)
>>> d.year
2022
>>> d.month
6
>>> d.day
6
>>> d.weekday()
0
>>> d.isoweekday()
1
>>> d.max
datetime.date(9999, 12, 31)
>>> d.min
datetime.date(1, 1, 1)
>>> d.ctime()
'Mon Jun 6 00:00:00 2022'
>>> d.timetuple()
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)
>>> d.strftime('%Y-%#m-%#d') #日期短格式
'2022-6-6'
>>> d.isoformat()
'2022-06-06'
>>> d.isocalendar()
(2022, 23, 1) #当年第23周第1天
>>> d.resolution
datetime.timedelta(days=1)
>>> d + dt.timedelta(2)
datetime.date(2022, 6, 8)
>>> d.toordinal()
738312
>>> d-d.min
datetime.timedelta(days=738311)
>>> d - dt.timedelta(d.toordinal()-1)
datetime.date(1, 1, 1)
>>> d.max-d
datetime.timedelta(days=2913747)
>>> dt.date(2023,1,1)-d
datetime.timedelta(days=209)
datetime.date(2022, 6, 6)
>>> d.replace(2023)
datetime.date(2023, 6, 6)
>>> d.replace(d.year,7)
datetime.date(2022, 7, 6)
>>> d.replace(d.year,d.month,8)
datetime.date(2022, 6, 8)
>>> d.replace(d.year,7,8)
datetime.date(2022, 7, 8)
>>> d.replace(2002,7,8)
datetime.date(2002, 7, 8)
>>> d
datetime.date(2022, 6, 6) #d未变更

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

>>> lst = [1,2,3,4,5]
>>> lst
[1, 2, 3, 4, 5]
>>> lst[3:3] = [0]
>>> lst
[1, 2, 3, 0, 4, 5]
>>> lst[3] = [0] # 对比
>>> lst
[1, 2, 3, [0], 4, 5]
>>> lst[3:4] = [] # 删除索引为3的元素
>>> lst
[1, 2, 3, 4, 5]
>>> lst[3:3] = [] # 这样lst没有变动
>>> lst
[1, 2, 3, 4, 5]
>>> lst[3:3] = [6,7,8]
>>> lst
[1, 2, 3, 6, 7, 8, 4, 5]
>>> lst[3:6] = [] # 恢复原状
>>> lst
[1, 2, 3, 4, 5]
>>> lst[-1:] = [7,8,9] # 列表去尾相接
>>> lst
[1, 2, 3, 4, 7, 8, 9]
>>> lst[4:] = [5] # 恢复原状
>>> lst
[1, 2, 3, 4, 5]
>>> lst[1:4] = [0, 0, 0] # 替换
>>> lst
[1, 0, 0, 0, 5]
>>> lst[2:3] = [1, 1] # 替换+插入
>>> lst
[1, 0, 1, 1, 0, 5]
>>> lst.insert(3, 2) # 单个元素插入等价于 lst[3:3]=[2]
>>> lst
[1, 0, 1, 2, 1, 0, 5]
>>>
>>> lst = [*range(1,6)]
>>> lst[-1:] = range(1,6)[::-1]
>>> lst
[1, 2, 3, 4, 5, 4, 3, 2, 1]
>>> lst[:4] = [] # 删除前面的字符
>>> lst
[5, 4, 3, 2, 1]

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

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

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

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

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

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

L0 = [3, 21, 24, 30, 36, 43, 46, 71, 82, 84, 96]
L1 = [7, 15, 22, 23, 32, 39, 41, 51, 74, 76, 87, 89]
L2 = [1, 18, 27, 31, 34, 35, 37, 48, 53, 57, 58, 81, 85, 97, 100]

L = [list(i) for i in (L0, L1, L2)]
res = []
while sum(map(lambda x:len(x),L)):
t, dic = [], {}
for i in range(len(L)):
if L[i]:
dic[L[i][0]] = i
t.append(L[i][0])
res.append(min(t))
L[dic[min(t)]][:1] = []

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 |  
 |  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)


推荐阅读
author-avatar
李辰1990
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有