![](/img/trans.png)
[英]How can i check in first List index 1 is greater than second list index 0, and first List index 2 is greater than second list index 1. and so on
[英]How to check index if the N'th index should be greater than previous
我想運行一個從0到1000的循環我想要打印低於前一個數字的數字“ex:123 3大於2而2大於1所以打印123”我嘗試從1到100以及如何檢查1000或更多的數字
我試圖將int輸入轉換為列表並檢查2位數
no=int(input())
lis=[]
num_lis=[]
le=0
for i in range(10,no):
lis=str(i)
num_lis=[int (x)for x in lis]
le=len(num_lis)-1
if num_lis[le]>num_lis[le-1]:
print(i)
從1到100沒有問題我想檢查三個數字,如1 <2 <3如果正確打印我的代碼只檢查最后兩位數如何檢查三和四位數
您可以創建一個函數來驗證數字的數字是否已排序:
def int_sorted(i):
s = str(i)
return s == ''.join(sorted(s, key=int))
print(int_sorted(123))
print(int_sorted(1234))
print(int_sorted(4234))
產量
True
True
False
注意, sorted(s, key=int)
通過使用sorted的key
參數,根據每個數字的int值對s
(數字串)進行排序 。 此功能獨立於位數工作。
如果它必須大於嚴格,你可以這樣做:
def int_sorted(i):
s = str(i)
sorted_s = sorted(s, key=int)
return s == ''.join(sorted_s) and all(int(c) < int(n) for c, n in zip(sorted_s, sorted_s[1:]))
print(int_sorted(123))
print(int_sorted(1234))
print(int_sorted(4234))
print(int_sorted(99))
產量
True
True
False
False
打印所有低於后的數字:
如果下一個數字較大,您可以簡單地記住一個數字並打印出來:
number = None
while number is None:
number = int(input("Input a number: "))
number = str(number)
last_digit = int(number[0])
for s in number[1:]:
this_digit = int(s)
if this_digit > last_digit:
print(last_digit, end="")
last_digit = this_digit
print(last_digit)
輸出12354
:
1235
這將打印低於下一個的所有數字。
檢查數字是否“按升序排列”:
要輕松檢查,您可以使用zip()
。 字符'0123456789'
按此順序進行比較: '0'<'1'<'2'<'3'<'4'<'5'<'6'<'7'<'8'<'9'
- 否需要將其轉換為整數,只需比較字符“按原樣”:
def IsIncreasing(number):
n = str(number)
return all(a<b for a,b in zip(n,n[1:]))
這是如何工作的 ?
它使數字和數字的元組移動了1:
"123456789"
"23456789"
==> ('1','2'),('2','3'),...,('7','8'),('8','9') as generator of tuples
並使用all()
確保所有第一個元素小於第二個元素
例:
for k in [1234,1,123456798]:
print(k,IsIncreasing(k))
輸出(重新格式化):
1234 True
1 True
123456798 False
沒有必要通過排序進行比較,這需要更多的計算。
測試從1到1000的所有數字:
您可以使用IsIncreasing()
函數創建一個從1到1000的所有“增加”數字的列表:
get_all_up_to_1000 = [k for k in range(1,1001) if IsIncreasing(k)]
print( *(f"{k:>3}," for k in get_all_up_to_1000))
輸出:
1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15,
16, 17, 18, 19, 23, 24, 25, 26, 27, 28, 29, 34, 35,
36, 37, 38, 39, 45, 46, 47, 48, 49, 56, 57, 58, 59,
67, 68, 69, 78, 79, 89, 123, 124, 125, 126, 127, 128, 129,
134, 135, 136, 137, 138, 139, 145, 146, 147, 148, 149, 156, 157,
158, 159, 167, 168, 169, 178, 179, 189, 234, 235, 236, 237, 238,
239, 245, 246, 247, 248, 249, 256, 257, 258, 259, 267, 268, 269,
278, 279, 289, 345, 346, 347, 348, 349, 356, 357, 358, 359, 367,
368, 369, 378, 379, 389, 456, 457, 458, 459, 467, 468, 469, 478,
479, 489, 567, 568, 569, 578, 579, 589, 678, 679, 689, 789,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.