我有兩個清單
list1 = [1, 3, 5, 8]
list2 = [7, 10, 12]
和一些突破性的 int 值switchValue = 4
,我需要遍歷它的元素,list1而它的元素的值小于switchValue,然后遍歷完整的list2。我知道如何在分支中使用if和break宣告,else但我正在尋找一些更優化(推薦)的方式如何在 Python 2.7 中實作這一點,因為這些串列會非常大。此外,對串列進行了排序。
result應該1, 3, 7, 10, 12
list1 = [1, 3, 5, 8]
list2 = [7, 10, 12]
switchValue = 4
for i in list1:
if i < switchValue:
print(i)
else:
for j in list2:
print(j)
break
uj5u.com熱心網友回復:
for i in list1:
if i >= switchValue:
break
print(i)
for i in list2:
print(i)
這真的是你想要的。迭代list1直到找到特定值,然后停止迭代list1。然后遍歷完整的list2. 這兩件事似乎是完全獨立的動作,因此沒有必要將它們交織在同一個回圈中。
請注意,這假定您總是想要迭代list2,而不僅僅是當您遇到時switchValue。你的問題在這一點上并不完全清楚。
第一次迭代可以用類似的東西來裝扮itertools.takewhile:
for i in takewhile(lambda i: i < switchValue, list1):
print(i)
for i in list2:
print(i)
要將兩者放入同一個回圈中,您可以chain:
for i in chain(takewhile(lambda i: i < switchValue, list1), list2):
print(i)
uj5u.com熱心網友回復:
因為您提到性能的重要性,所以此解決方案將為您節省一些資源。但不確定這是否適合您的實際生產資料和代碼。
list1 = [1, 3, 5, 8] # we assume this is sorted
list2 = [7, 10, 12]
switchValue = 4 # Assuming switchValue <= list1[-1]
# find index of real switchValue
switch_index = None
while not switch_index:
try:
print('Try to find switch_index for {}.'.format(switchValue))
switch_index = list1.index(switchValue)
print('Real switch value is {} at index {}.'
.format(switchValue, switch_index))
except ValueError: # value not found
# try the next higher value
switchValue = switchValue 1
for val in list1[:switch_index]:
print('Current list1 value = {}'.format(val))
# process what ever you have to
for val in list2:
print('Current list2 value = {}'.format(val))
輸出是
Try to find switch_index for 4.
Try to find switch_index for 5.
Real switch value is 5 at index 2.
Current list1 value = 1
Current list1 value = 3
Current list2 value = 7
Current list2 value = 10
Current list2 value = 12
解釋
做兩while not switch_index件事。它找到 real 的真實值和索引switchValue。這使您不必if在每次迭代中執行一次。這里也沒有if,只有一個例外處理,它比if.
下一部分for val in list1[:switch_index]:不使用switch_index來找出何時停止迭代。它只是剪切list1at 然后switch_index然后迭代該剪切串列。無需消耗性能if。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452168.html
標籤:Python python-2.7
上一篇:在Webgl構建時出現決議錯誤,而同一專案在編輯器中作業正常
下一篇:str.encode(encoding='utf-8',errors='strict')是否有可能引發UnicodeError?
