问题
I have a list of integers which I have extracted from a string of text, so when I print the list (which I have called test
) I get:
['135', '2256', '1984', '3985', '1991', '1023', '1999']
and I want to print or make a new list containing only numbers within a certain range, e.g. between 1000-2000. I tried the following, but it still returns all of the items in my original list.
for i in test:
if i>1000:
print i
elif i<2000:
print i
And I can't work out why it would still be printing numbers below 1000 or above 2000.
回答1:
First convert your list of strings to a list of ints:
ints_list = [int(x) for x in test]
Then you can filter this list however you would like. We can do this with a list comprehension like the above line. Notice the and
that makes it so that the number has to meet both conditions to be in the list.
filtered_list = [x for x in ints_list if x > 1000 and x < 2000]
回答2:
It's ambiguous whether you are using Python 2 or 3. You tagged Python 3, but in this case you should be getting a TypeError
instead of semantically incorrect output. This answer works for both versions of Python.
test
is a list of strings, but you want to do integer comparisons.
Build a list of integers first, then apply your algorithm.
>>> test = ['135', '2256', '1984', '3985', '1991', '1023', '1999']
>>> test_ints = [int(x) for x in test] # or test_ints = map(int, test)
>>> for i in test_ints:
... if i > 1000:
... print(i)
... elif i < 2000:
... print(i)
...
135
2256
1984
3985
1991
1023
1999
Now the code runs, but still has bugs. Note how 135
is falsely printed, because it is not greater than 1000
but smaller than 2000
.
A bug free version could look like this:
>>> for i in test_ints:
... if 1000 < i < 2000:
... print(i)
...
1984
1991
1023
1999
... and if you want to build a list instead of just printing the filtered elements, create an empty list and append
the hits.
>>> result = []
>>> for i in test_ints:
... if 1000 < i < 2000:
... result.append(i)
...
>>> result
[1984, 1991, 1023, 1999]
If you are already comfortable with list comprehensions, the shorter version to write this looks like this:
>>> result = [i for i in test_ints if 1000 < i < 2000]
>>> result
[1984, 1991, 1023, 1999]
Alternatively, the conversion to int
could be done on the fly by mapping the int
builtin onto your original list test
inside a single comprehension.
>>> result = [i for i in map(int, test) if 1000 < i < 2000]
>>> result
[1984, 1991, 1023, 1999]
Personally, I prefer the last solution for its brevity.
回答3:
Let's start by stating that this just cannot run under python 3 because you cannot compare strings (as contained in your list) to integers anymore without error.
On python 2, all i>1000
tests succeed.
>>> "12">1000
True
Fortunately this has been fixed in python 3 and it avoids those mistakes:
>>> "12">1000
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: unorderable types: str() > int()
I suggest to test integers (if you want to keep your list elements as strings, else convert beforehand):
lst = ['135', '2256', '1984', '3985', '1991', '1023', '1999']
print([x for x in lst if 1000<int(x)<2000])
or convert to integer first, then filter:
lst = [int(x) for x in lst]
print([x for x in lst if 1000<x<2000])
using chained comparisons which are very readable in this case.
回答4:
Check this:
>>> l = ['135', '2256', '1984', '3985', '1991', '1023', '1999']
>>> for i in l:
if (int(i) > 1000) and (int(i) < 2000):
print i
- converting first str to int and then comparing your condition
回答5:
You are currently facing two problems: your numbers are not really integers
, but strings
, and the if
condition isn't working as you expect.
Starting with the integer
problem, you can see that you're handling strings
which represents a number by printing their type at the start of the for
loop:
for i in test:
print type(i) # string!
in python is pretty easy to convert strings
into integers
:
i = int(i) # now 'i' is an integer
In this chunk of code, python will try to convert the string into an integer, and if he can't (i.e. int("Hello World!")
), it raises an error.
The second problem is in the logic behind your if
condition, but fortunately Python is really similar to english, so we can easily translate our code into spoken language:
for each number in my list,
if the number is higher than 1000, print the number
else if the number is lower than 2000, print the number
So now we can simulate some cases:
our number is 1337
is the number higher than 1000? YES! so - print the number
or
our number is 42
is the number higher than 1000? NO! go on
is the number lower than 2000? YES! print the number
and at last:
our number is 2048
is the number higher than 1000? YES! print the number
so now the problem seems clear.
the english sentence
that you want to transform into code is:
for each number in my list, if the number is higher than 1000 and the number is lower than 2000, print the number
I am not going to write you the code, but in other answers you can find it
回答6:
That is because you are comparing a string
with an integer
and if the number is not more than 1000
for example the first value: 135
, if move to the elif
in which 135
< 2000
.
What you can try is:
for i in test:
if 1000 < int(i) < 2000:
print i
That is given that all your values are integer values.
来源:https://stackoverflow.com/questions/52778594/specific-range-within-a-list-python