將第一個串列的最后一個元素與其右側串列的第一個元素或 Python 3.4.3 中的“鄰居”進行比較
基本上,我正在做的是遍歷每個串列并取出第一個和最后一個元素并將它們全部放入一個串列中。然后,我取出該串列并將其全部向下移動并拍打前面的最后一個元素并將原始元素和切片一起壓縮。我比較生成的每個元組的第一個和第二個元素。我需要所有元素都相等,或者至少我需要檢查那個條件。
arr = [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ]
^ == ^
# it has to compare the first of the first and the last of the last
arr = [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ]
^ ^ ^ ^ ^ ^
# it has to compare all the elements that "touch", or are next to each other
不正確的輸出(我產生的)
[(9, 9), (4, 9), (4, 4), (1, 4), (1, 1), (1, 1), (1, 1), (9, 1)]
# (4, 9) (1, 4) and (1,1 count of 2 not 3) (9, 1)
# shouldn't be in the answer
應該產生:
[(9, 9), (4, 4), (1, 1), (1, 1), (9, 1)] #edited
源代碼
def check(arr):
res = []
for l in lst:
front, back = l[0], l[-1]
res.append(front)
res.append(back)
z = zip(temp, [res[-1]] res[:-1])
print(z)
check( [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ] )
我看到問題在于它正在獲取我的 arr 中第一個串列的第一個和最后一個元素并比較它們。(例如[9, 2, 3, 4],比較9and 4,它不應該。我不知道如何解決這個問題,因為我沒有辦法檢查它們是否來自同一個陣列。
我查看了這個堆疊溢位問題和其他一些問題,但是他們沒有專門回答我NEEDS。感謝您的幫助:)
uj5u.com熱心網友回復:
假設您的預期輸出中有錯字,您可以使用zip:
lst = [[9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9]]
output = [(xs[-1], ys[0]) for xs, ys in zip((lst[-1], *lst), lst)]
print(output) # [(9, 9), (4, 4), (1, 1), (1, 1)]
uj5u.com熱心網友回復:
如果您的 Python 版本是 3.10 ,請考慮itertools.pairwise:
>>> arr = [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ]
>>> [(i[-1], j[0]) for i, j in pairwise(arr[-1:] arr)]
[(9, 9), (4, 4), (1, 1), (1, 1)]
要確定它們是否都相同,請使用all:
>>> all(i[-1] == j[0] for i, j in pairwise(arr[-1:] arr))
True
uj5u.com熱心網友回復:
def check(arr):
if len(arr) < 2:
return False
elif len(arr) == 2:
return arr[0][0] == arr[-1][-1] and arr[0][-1] == arr[1][0]
res = []
for i in range(1, len(arr)):
ele1, ele2 = arr[i-1][-1], arr[i][0]
res.append(ele1 == ele2)
res.append(arr[0][0] == arr[-1][-1])
return all(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/483721.html
標籤:Python 数组 python-3.x 循环 片
下一篇:如何在回圈中系結樣式單擊
