[英]Checking numbers inbetween integers in a list
我有一個列表,其中50個隨機數,范圍從1到1000,從最小到最大排序。 我想找到這些數字之間的任何數字,但不包括它們。 問題是當數字直接相互跟隨(100,101,102)時,它們仍然會被打印,即使不應該打印。 (代碼用Python 3.2.3編寫)
我嘗試將列表的第一個整數與第二個整數進行比較,將第一個整數與第一個整數相加,直到它最終變得與第二個一樣大。 然后我會比較第二個和第三個等。
list = [98, 100, 101, 102, 103, 110, ... ]
position_counter_1 = 0
position_counter_2 = 1
position_1 = 0
position_2 = 1
while position_counter_2 < len(list):
if list[position_1] + 1 != list[position_2] :
while list[position_counter_1] <= list[position_counter_2] - 1 :
list[position_counter_1] = list[position_counter_1] + 1
print(list[position_counter_1])
if list[position_counter_1] >= list[position_counter_2] - 1 :
position_counter_1 = position_counter_1 + 1
position_counter_2 = position_counter_2 + 1
輸出為99 101 102 103 104 105 106 107 108 109
,應為99 104 105 106 107 108 109
。
此外,我得到以下錯誤按摩,這不是那么糟糕,因為它只在循環完成時出現在這里它是:
while list[position_counter_1] <= list[position_counter_2] - 1 :
IndexError: list index out of range
它是Python,不要復雜化。 :)
mylist = [98, 100, 101, 102, 103, 110]
[num for num in range(mylist[0]+1, mylist[-1]) if num not in mylist]
Python 3 range
創建第一個參數(包括它)和第二個參數(不包括它)之間的所有整數的迭代器。 所以這個列表解析從上述任務創建的所有數字的一個新的列表( mylist[0]
返回第一個和mylist[-1]
返回的最后一個整數),但不包括在列表中已經出現(那些if num not in mylist
條件下。)
我建議沒有嵌套循環的更簡單的方法:
my_list = [98, 100, 101, 102, 103, 110, ... ]
for i in range(1000):
if i not in my_list:
print(i)
list = [98, 100, 101, 102, 103, 110 ]
for i in range (list[0], list[-1]):
if i not in list:
print (i)
輸出:
99
104
105
106
107
108
109
或列表理解
print ([i for i in range (list[0], list[-1]) if i not in list])
你可以用套裝:)
list1 = [98, 100, 101, 102, 103, 110]
full = set(range(list1[0], list1[-1] + 1))
result = full - set(list1)
print(result)
# {99, 104, 105, 106, 107, 108, 109}
在這里,我正在創建一個列表,其中包含列表range
之間的所有數字范圍,總是假定它是有序的,否則您可以使用sorted()
。 然后將它投射到設置並只是做一些不同的集合。
您可以使用范圍 (開始,停止,步驟)功能:
開始 - 開始的位置。 默認值為0
停止 - 結束,不包括在內。
步驟 - 增量。 默認值為1
list = [98, 100, 101, 102, 103, 110]
for i in range(1,1001):
if i not in list:
print(i)
輸出是:
... 99 104 105 106 107 108 109 ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.