簡體   English   中英

如何比較列表中的4個連續元素?

[英]How to compare 4 consecutive elements in a list?

我是編碼的新手,所以如果我要問的內容很簡單或沒有多大意義,我會提前道歉,但我會盡我所能詳細說明。 首先,這不是針對任何工作或項目的,我只是在學習學習一些使我滿意的編碼。 我一直在嘗試找到一些現實生活中的問題以應用於編碼(大多數是偽代碼,但是python語言對我來說也是可以理解的)。

我希望能夠有一個x元素列表,並依次比較其中的4個元素。

例如, myList = [a, b, c, d, e, f, g, h, i, j, k, l]

首先,我想比較a,b,c和d。 如果b>a, c>b, d>c和d>都是前3個( d>a, d>b, d>c ),我想做些其他的事情,否則轉到下一個比較。

然后我想比較b,c,d和e。 類似地,如果c>b, d>c, e>d和e>都是前三個( e>b, e>c, e>d ),我想做些其他的事情,否則轉到下一個比較。

如果我的列表包含無限元素怎么辦? myList = [:]我從哪里開始? 我必須有一個起點嗎?

我猜想我必須使用for循環來遍歷列表,但老實說我無法弄清楚如何遍歷前4個元素,然后在4個元素批次中從第二個元素繼續。

由於我目前正在研究數組和列表,因此可能缺少某些功能? 或者我只是我的大腦可以抓住它。

我嘗試查看stackoverflow中的其他帖子,但老實說,我無法從其他人的答案中找出來。 我將不勝感激任何幫助或指導。

提前致謝。

您可以使用內置的all()函數來解決此問題:

myList = [5, 4, 3, 6, 3, 5, 6, 2, 3, 10, 11, 3]

def do_somthing():
    #your code here
    pass

for i in range(len(myList)-4):
     new_list = myList[i:i+4] #here, using list slicing to jump ahead four elements.
     if all(new_list[-1] > b for b in new_list[:-1]) and all(new_list[:-1][c] > new_list[:-1][c+1] for c in range(len(new_list)-2)):
         do_something()
L = [...]
# get all the valid indices of the elements in the list, except for the last 4. These are the indices at which the 4-element windows start
for i in range(len(L)-4):
    window = L[i:i+4]  # the 4 elements you want to compare
    print("I am considering the elements starting at index", i, ". They are:", window)
    a,b,c,d = window
    if d>a>b>c<d and d>b:
        print("The checks pass!")

現在,有一種更簡單的方法可以執行此操作:

for a,b,c,d in (L[i:i+4] for i in range(len(L)-4):
    if d>a>b>c<d and d>b:
        print("The checks pass!")

由於可以索引列表,因此從索引0開始,比較第0,第(0 + 1),(0 + 2)和第(0 + 3)個元素。 然后,在下一輪中,將索引增加到1,並比較第1個,第(1 + 1)個,第(1 + 2)個和第(1 + 3)個元素,依此類推。 對於第n輪,您比較第n,n + 1,n + 2和第(n + 3)個元素,直到到達末尾的第4個元素。 通常,這就是“每次從長度為n的序列中測試m個元素”之類的方法,您可以輕松地將此模式擴展為矩陣或3d數組。 您在其他答案中看到的代碼基本上都在執行此操作,並且Python中的某些功能使此工作非常容易。

現在,“如果列表包含無限元素會怎樣?” 好吧,那么您需要一個生成器,我認為在這個階段它會有點先進,但是概念很簡單:您讓函數讀取(可能是無限的)循環中的無限元素流,並設置一個游標在其中之一上,每次返回( yield )光標下方的元素以及其后的3個元素,並在下一個循環開始之前將光標增加一個:

def unsc_infinity(somelist):
    cur = 0
    while True:
        yield somelist[c:c+4]
        cur = cur + 1

infinity_reader = unsc_infinity(endless_stream)
next(infinity_reader)
# gives the 0, 1, 2, 3 th elements in endless_stream
next(infinity_reader)
# gives the 1, 2, 3, 4 th elements in endless_stream
next(infinity_reader)
# ...

您也可以遍歷該生成器:

for a, b, c, d in unsc_infinity(endless_stream):
    if d>a>b>c<d and d>b:
        do_something()

希望這對您建立有關如何解決此類問題的心理模型有所幫助。

要一次從迭代器中消耗一項並對4個滯后元素進行操作,請嘗試使用圓形緩沖區:

# make a generator as example of 'infinte list'
import string
agen = (e for e in string.ascii_lowercase)

# initialize len 4 circle buffer
cb = [next(agen) for _ in range(4)]  # assumes there are at least 4 items
ptr = 0  # initialize circle buffer pointer

while True:
    a,b,c,d = (cb[(i+ptr)%4] for i in range(4))  # get current 4 saved items

    # some fuction here
    print(a,b,c,d)  

    # get next item from generator, catch StopIteration on empty
    try:
        cb[ptr] = next(agen)
    except StopIteration:
        break
    ptr = (ptr + 1)%4  # update circle buffer pointer
a b c d
b c d e
c d e f
d e f g
e f g h
f g h i
g h i j
h i j k
i j k l
j k l m
k l m n
l m n o
m n o p
n o p q
o p q r
p q r s
q r s t
r s t u
s t u v
t u v w
u v w x
v w x y
w x y z

“某些功能”也可能包含停止條件:

 # random.choice() as example of 'infinte iterator'
import string
import random
random.choice(string.ascii_lowercase)

# initialize len 4 circle buffer
cb = [random.choice(string.ascii_lowercase) for _ in range(4)]  # assumes there are at least 4 items
ptr = 0  # initialize circile buffer pointer


while True:
    a,b,c,d = (cb[(i+ptr)%4] for i in range(4))  # get current 4 saved items

    # some fuction here
    print(a,b,c,d)
    if a<b<c<d:  # stopping condition
        print("found ordered string: ", a,b,c,d)   
        break

    # get next item from generator, catch StopIteration on empty
    try:
        cb[ptr] = random.choice(string.ascii_lowercase)
    except StopIteration:
        break
    ptr = (ptr + 1)%4  # update circle buffer pointer
o s w q
s w q k
w q k j
q k j r
k j r q
j r q r
r q r u
q r u v
found ordered string:  q r u v

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM