簡體   English   中英

從列表中隨機打印 integer 編號 python

[英]print integer number from list random python

我有一個小問題,當我在列表中輸入相同的數字時,我生成隨機數到 50 個列表后,它不會打印“找到匹配”。 它總是會向我發送“未找到匹配項”。 你們能解釋一下代碼有什么問題嗎?

import random

mylist=[]

for i in range (50):
 x= random.randint(100,999)
 mylist.append(x)

print(mylist)

p = input('Enter an integer number: ')

for i in range(len(mylist)):
    if p == mylist[i]:
        print('Match found at position')
        break
else:
    print('no match found')

output 示例

[836, 569, 378, 788, 847, 584, 404, 159, 362, 271, 151, 100, 702, 414, 867, 213, 194, 553, 946, 930, 777, 143, 143, 879, 724, 752, 431, 416, 944, 509, 752, 211, 713, 951, 882, 836, 710, 998, 447, 892, 720, 210, 364, 768, 603, 456, 540, 727, 346, 153]
Enter an integer number: 836
no match found
>>> 

我剛開始學習編碼,所以如果你們能解釋一下,我很樂意理解以供將來參考:)

使用int()對輸入進行類型轉換,然后打印匹配的索引

import random

mylist=[]

for i in range (50):
 x= random.randint(100,999)
 mylist.append(x)

print(mylist)

p = input('Enter an integer number: ')

for i in range(len(mylist)):
    if int(p) == mylist[i]:
        print('Match found at position ' + str(i))
        break
    else:
        print('no match found')

除了更正注釋中提到的類型轉換之外,您甚至不需要循環來查找匹配項。 使用 python in的強大功能。 你可以用這個替換你的整個搜索循環:

if int(p) in mylist:
    print('Match found at position')
else:
    print('no match found')

如果您需要打印列表中p的索引,請使用以下命令:

try: 
  print('Match found at position ',mylist.index(int(p)))
except:
  print('no match found')

您也可以使用 numpy package 創建一個沒有循環的隨機整數列表:

import numpy as np
mylist = np.random.randint(100, high=999, size=50).tolist()

因此,您的整個代碼將如下所示:

import numpy as np

mylist = np.random.randint(100, high=999, size=50).tolist()
p = input('Enter an integer number: ')
if int(p) in mylist:
    print('Match found at position')
else:
    print('no match found')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM