[英]Python searching list thats inputted by user
Hi im trying to write a program which uses a repetition statement to allow users to enter 5 numbers and stores them in a list.Then allow the user to search the list for a number entered by the user and indicate whether the number has been found or not. 嗨,我试图编写一个程序,该程序使用重复语句来允许用户输入5个数字并将其存储在列表中,然后允许用户在列表中搜索用户输入的数字并指出是否已找到该数字或不。 Im quite stuck on this one, I've made as much of an effort as i can
我非常坚持这一点,我已经尽了最大的努力。
data =raw_input('Please input 5 numbers: ')
print data
search =raw_input('Search for the numer: ')
for sublist in data:
if sublist[1] == search:
print "Found it!", sublist
break
data
is a string, the for
loop will loop over every character in this string. data
是一个字符串, for
循环将遍历该字符串中的每个字符。 That's probably not what you want. 那可能不是您想要的。
If you want to find an integer in a list of integers, split
the input on whitespace and convert each to an integer using int
. 如果要在整数列表中找到一个整数,请在空白处
split
输入,然后使用int
将每个输入转换为整数。
ints = [int(x) for x in data.split()]
if int(search) in ints:
print "Found it"
You might try something like this 您可以尝试这样的事情
numbers = []
while len(numbers) < 5:
number = raw_input('Please input 5 numbers: ')
if number.isdigit():
numbers.append(int(number)) #may want to use float here instead of int
else:
print "You entered something that isn't a number"
search = raw_input('Search for the numer: ')
if int(search) in numbers:
print "Found it!"
your code indicates that you may be using sublists but it is unclear how you are creating them. 您的代码表明您可能正在使用子列表,但不清楚如何创建它们。
Issue 1 : This line stores the input as a string in the variable data
. 问题1 :此行将输入作为字符串存储在变量
data
。
data =raw_input('Please input 5 numbers: ')
At this point it is necessary to split the string into a list, and converting the elements to integers. 此时,有必要将字符串拆分为列表,然后将元素转换为整数。 If the user inputs numbers separated by a space, you can do:
如果用户输入的数字以空格分隔,则可以执行以下操作:
data_list = data.split() # if the numbers are comma-separated do .split(',') instead
int_list = [int(element) for element in data_list]
Issue 2: The users search input should be converted to an integer 问题2:用户搜索输入应转换为整数
search =raw_input('Search for the numer: ')
search_int = int(search)
Issue 3: There is no need for indexing the sublist as you've attempted sublist[1]
. 问题3:无需像尝试使用
sublist[1]
那样为子列表建立索引。 The for-loop should then be: for循环应为:
for sublist in int_list:
if sublist == search_int:
print "Found it!", sublist
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.