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列表里面根据一定的条件挑选元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020 idea 查看内存消耗_ide
- 下一篇: matlab源代码 语义相似度计算,如何