![](/img/trans.png)
[英]Using python and selenium to get elemnts in <div> to a list or dataframe
[英]Check if python list elemnts respect a pattern
我有一個看起來像的列表:
L = [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1]
我想檢查序列 2-1-2 是否始終受到尊重,或者我在某處有異常值。 有沒有一種簡單的方法可以用 python 做到這一點?
from itertools import cycle
L = [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
seq = cycle([2, 1])
for idx, el in enumerate(L):
if not el == next(seq):
raise ValueError(f"Sequence not followed at index {idx}")
“2-1-2 始終受到尊重”究竟是什么意思?
我假設您想檢查L
是否是2
和1
的交替序列,從2
開始。
這很容易檢查:
def check(L):
if len(L) < 3:
return False
even_indices_all_two = set(L[::2]) == {2}
odd_indices_all_one = set(L[1::2]) == {1}
return even_indices_all_two and odd_indices_all_one and L[-1] == 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.