我會得到一個數字列表,每行都有自己的一行(比如0 -100)。如何找到未列出或缺失的號碼?如何找到未列出或缺失的號碼?
5
A
回答
12
將它們全部添加到集合中。然後從1-100填充的集合中減去。這裏是一個0-9的例子:
>>> set(range(10)) - set([1, 4, 5, 6, 8, 2])
set([0, 9, 3, 7])
>>>
我有[1, 4, 5, 6, 8, 2]
列出。要找出範圍0-9中的哪些數字缺失,我創建了一個全部爲0-9的集合,然後從中減去集合[1, 4, 5, 6, 8, 2]
。並發現[0, 9, 3, 7]
失蹤。
集合對此非常有效。作爲一個額外的好處,重複將被優雅地處理。
1
如果L是號碼的列表,然後
set(L).difference(xrange(101))
保存從x範圍
In [1]: L=[1, 4, 5, 6, 8, 2]
In [2]: timeit set(range(101)) - set(L)
10000 loops, best of 3: 21.7 µs per loop
In [3]: timeit set(L).symmetric_difference(range(101))
100000 loops, best of 3: 14.2 µs per loop
In [4]: timeit set(L).difference(range(101))
100000 loops, best of 3: 9.73 µs per loop
+0
你也可以使用'difference','symmetric_difference'本質上是XOR –
+0
@Eli,好點,更快 –
0
這裏的使用關聯的awk
溶液創建一組(鍵值)陣列:
printf '%s\n' 1 4 5 6 8 2 |
awk -F " " -v first=0 -v last=9 '
BEGIN {
for(i=first; i<=last; i++)
array[i] = 0
}
{
for(i=1;i<=NF;i++)
array[$i] += 1
}
END {
for (num in array)
if (array[num] == 0) print num
}
'
- 首先,我們cre吃了一個給定範圍的所有數字,用作默認值爲0的單個鍵。
- 然後每個輸入數字都被awk處理爲數組的一個鍵,以便數值遞增1.
- 在結束時,只有那些沒有增加的鍵被打印出來,即值爲0(因爲它們在輸入數字範圍中缺失)。
0
慶典:
# first set up an array containing the whole range
declare -a nums
for i in {0..100}; do
nums[$i]=1
done
# then read the file and remove the numbers from it
while read number; do
unset nums[$number]
done < file.with.numbers
# the remaining array keys are the numbers not found in the file
for number in "${!nums[@]}"; do
echo $number
done
相關問題
- 1. 找到缺失的號碼
- 2. SharePointOnlineCredentials缺失或未找到
- 3. Spark:找到缺失號碼的程序
- 4. 如何從seqentail號碼找出缺失的數字?
- 5. 在列表中找到一個缺失的號碼
- 6. 找到失蹤的號碼。從陣列
- 7. 如何在emacs中找到缺失或不匹配的大括號/ parens?
- 8. git找到缺失的代碼?
- 9. ModuleParse失敗或未找到
- 10. 查找列缺號
- 11. 如何找到缺失的索引?
- 12. 如何找到缺失的行?
- 13. 找到號碼時列出行
- 14. 找出缺失的日期
- 15. 圖像源未找到或ContentDescription缺少
- 16. 如何從SQL表中的列找到缺失的日期?
- 17. 如何找到VARIABLES只有缺失值?
- 18. Android查找缺少號碼
- 19. 如何找到2列之間的缺失數字?
- 20. 如何在Excel中找到缺失值的列
- 21. 查找重複,缺失號碼,在整數數組缺失順序
- 22. 構建失敗:未找到符號
- 23. 的Xcopy:參數無效號碼或文件未找到錯誤
- 24. 通過J2ME找到電話號碼或任何唯一號碼
- 25. AWK列出找到匹配的列號
- 26. 找到號碼列數改變編號
- 27. 使用.reduce查找序列中的缺失編號
- 28. 查找兩個列表中的缺失編號
- 29. 在未排序的序列中查找缺少的編號
- 30. 在明庫中查找缺失符號
你有沒有重複的數字?他們排序了嗎?這是功課嗎? :-) – juanchopanza
Python還是Bash? – Chetan