简体   繁体   English

从列表中随机打印 integer 编号 python

[英]print integer number from list random python

i have this little bit problem where after i generate random number to a list of 50 when i input the same number on the list, it does not print "match found".我有一个小问题,当我在列表中输入相同的数字时,我生成随机数到 50 个列表后,它不会打印“找到匹配”。 it will always send me "no match found".它总是会向我发送“未找到匹配项”。 can you guys explain what is wrong with the code.你们能解释一下代码有什么问题吗?

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')

example of output 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
>>> 

i just started learning coding so if u guys can explain it i would be happy to understand for future reference:)我刚开始学习编码,所以如果你们能解释一下,我很乐意理解以供将来参考:)

typecast your input with int() then print index that match使用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')

On top of correcting the type cast mentioned in comments, you do not even need a loop to find the match.除了更正注释中提到的类型转换之外,您甚至不需要循环来查找匹配项。 Use the powerful in in python.使用 python in的强大功能。 You can replace your entire search loop with this:你可以用这个替换你的整个搜索循环:

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

And if you need to print the index of p in the list, use this:如果您需要打印列表中p的索引,请使用以下命令:

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

And you can use numpy package to create a list of random integers without loop as well:您也可以使用 numpy package 创建一个没有循环的随机整数列表:

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

So your entire code will look like this:因此,您的整个代码将如下所示:

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