Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

python - Printing values from list within an input range

I have an unordered list, let's say:

lst = [12,23,35,54,43,29,65]

and the program will prompt the user to input two numbers, where these two numbers will represent the range.

 input1 = 22
 input2 = 55

therefore, 22 will be the lowest range and 55 will be the largest range. then with these two range, i want to print the values in the list within these range which are:

23
29
35
43
54

Here's my code:

def valRange(input1,input2,l):
n = len(l)
i = 0
upper = input2
lower = input1
while i<n:
    if (lower<=l[i]<=upper):
        l = l[i]
    i+=1
return l

print(valRange(input1,input2,lst))

I'm getting an error saying int object is not subscriptable. Am I comparing it right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are assigning an integer to variable l (previously it was a list) at line 8.

Then, in next iteration it tries to get i'th element of an integer. Which results in error of course.

Try this;

def valRange(input1,input2,l):
    result = []

    n = len(l)
    i = 0
    upper = input2
    lower = input1
    while i<n:
        if (lower<=l[i]<=upper):
            result.append(l[i])
        i+=1
    return result

print(valRange(input1,input2,lst))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...