欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

python 列表比较不同物质的吸热能力_python列表里面根据一定的条件挑选元素

发布时间:2024/7/23 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python 列表比较不同物质的吸热能力_python列表里面根据一定的条件挑选元素 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

update:

之前一版是错的,忽略了两层栈深还必须ticket、spce连续的要求

换个解法,代码有些冗长

#!/usr/bin/env python

# -*- coding: utf-8 -*-

def is_ticket(node):

return node.startswith('ticket')

def is_spec(node):

return node.startswith('spec')

def deal1(L):

if L:

node = L.pop(0) # 无论何种,都会使表长 -1

if is_ticket(node):

return node

return None

def deal2(L):

def match_ts(L):

node1, node2 = L[:2]

return is_ticket(node1) and is_spec(node2)

if len(L) < 2:

return False

elif match_ts(L):

del(L[:2]) # 表长 -2

return True

else:

return False

def deal4(L):

def match_ttss(L):

n1, n2, n3, n4 = L[:4]

return is_ticket(n1) and is_ticket(n2) and is_spec(n3) and is_spec(n4)

if len(L) < 4:

return False

elif match_ttss(L):

del(L[:4]) # 表长 -4

return True

else:

return False

def findout_no_spec_tickets(L):

res = []

while len(L):

if deal4(L):

continue

elif deal2(L):

continue

ret = deal1(L)

if ret:

res.append(ret)

return res

L =["ticket1","ticket2","spec1","spec2",

"ticket3","ticket4","spec3",

"ticket5","spec4","spec5",

"ticket6","ticket7","ticket8",

"ticket9","ticket10","spec6","spec7",

"ticket11","ticket12",

"ticket13","spec8",

"ticket14","spec9",

"ticket15","ticket16","ticket17",

"ticket18","spec1",

"ticket19",

"ticket20","spec2",

"ticket21"]

if __name__ == '__main__':

res = findout_no_spec_tickets(L)

print(res)

还有个短的写法, 无非是前向判断,滤出非'ts', 'ttss':

def is_ticket(node):

return node.startswith('ticket')

def find(L):

length = len(L)

for i in range(length):

if is_ticket(L[i]):

if i == length - 1:

yield L[i]

elif length - 4 < i < length - 1:

if is_ticket(L[i+1]):

yield L[i]

else:

if is_ticket(L[i+1]) and (is_ticket(L[i+2])

or is_ticket(L[i+3])):

yield L[i]

if __name__ == '__main__':

print(list(find(L)))

--------------------------------before---------------------------------------

用栈是最优的

def findout_no_spect(L):

def is_ticket(s): return s.startswith("ticket")

def is_spec(s): return s.startswith("spec")

no_spec_tickets = []

stack = []

for i in L:

if stack and is_spec(i): stack.pop()

if is_ticket(i): stack.append(i)

if len(stack) > 2: no_spec_tickets.append(stack.pop(0))

no_spec_tickets.extend(stack)

return no_spec_tickets

输出

>>> find_no_spect(L)

['ticket6', 'ticket7', 'ticket8', 'ticket11', 'ticket12']

总结

以上是生活随笔为你收集整理的python 列表比较不同物质的吸热能力_python列表里面根据一定的条件挑选元素的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。