我現在在 python 中,所以任何幫助或建議表示贊賞。
我想要做的是,有兩個串列(不一定是倒置的)。
例如:
l1 = [1,2,3,4,5]
l2 = [5,4,3,2,1]
比較它們以回傳公共值,但不像任何人通常會做的那樣,在這種情況下,回傳將是串列的所有元素,因為它們是相同的,只是倒置了。我要比較的是,相同的東西,但就像分階段或串列的半部分,并檢查是否有任何巧合,如果有,則回傳該元素,如果沒有,請繼續查看下一個團體。
例如:第一次迭代,將檢查(具有先前定義的串列:
l1 = [1]
l2 = [5]
#is there any coincidence until there? -> false (keep looking)
第二次迭代:
l1 = [1, 2]
l2 = [5, 4]
#is there any coincidence until there? -> false (keep looking)
第三次迭代:
l1 = [1, 2, 3]
l2 = [5, 4, 3]
#is there any coincidence until there? -> true (returns 3, which is the element where the coincidence was found)
所有這些都需要實作雙向搜索,但我發現自己目前卡在這一步,因為我還不太習慣 for 回圈和串列處理。
uj5u.com熱心網友回復:
您可以在同一回圈中比較兩個串列的元素:
l1 = [1,2,3,4,5]
l2 = [5,4,3,2,1]
for i, j in zip(l1, l2):
if i == j:
print('true')
else:
print('false')
uj5u.com熱心網友回復:
看起來您真的在問:在同一索引處共有l1的第一個元素(的索引)是什么?l2
解決方案:
next((i, a) for i, (a, b) in enumerate(zip(l1, l2)) if a == b)
這是如何作業的:
zip(l1, l2)l1將和中的元素配對l2,生成元組enumerate()獲取這些元組,并跟蹤索引,即(0, (1, 5),(1, (2, 4))等。for i, (a, b) in ..生成那些索引和值元組對if a == b確保僅產生值匹配的那些索引和值next()從可迭代中獲取下一個元素,您對匹配條件的第一個元素感興趣,所以這就是next()讓您到達這里的原因。
作業示例:
l1 = [1, 2, 3, 4, 5]
l2 = [5, 4, 3, 2, 1]
i, v = next((i, a) for i, (a, b) in enumerate(zip(l1, l2)) if a == b)
print(f'index: {i}, value: {v}') # prints "index: 2, value: 3"
如果您對索引不感興趣,而只是對它們共同的第一個值感興趣:
l1 = [1, 2, 3, 4, 5]
l2 = [5, 4, 3, 2, 1]
v = next(a for a, b in zip(l1, l2) if a == b)
print(v) # prints "3"
uj5u.com熱心網友回復:
另一種解決方案,使用any() :=運算子:
l1 = [1, 2, 3, 4, 5]
l2 = [5, 4, 3, 2, 1]
if any((val := a) == b for a, b in zip(l1, l2)):
print("There is common value =", val)
else:
print("There isn't common value")
印刷:
There is common value = 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/516740.html
標籤:Python列表
