简体   繁体   English

列表中的特定范围(python)

[英]Specific range within a list (python)

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: 我有一个从文本字符串中提取的整数列表,因此当我打印列表(我称之为test )时,我得到:

['135', '2256', '1984', '3985', '1991', '1023', '1999']

and I want to print or make a new list containing only numbers within a certain range, eg between 1000-2000. 我想打印或制作一个仅包含特定范围内(例如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. 而且我不知道为什么它仍然会打印低于1000或高于2000的数字。

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. 请注意and ,因此编号必须同时满足两个条件。

filtered_list = [x for x in ints_list if x > 1000 and x < 2000]

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. 让我们首先说明一下,它不能在python 3下运行,因为您不能再将字符串(包含在列表中)与整数进行比较而不会出错。

On python 2, all i>1000 tests succeed. 在python 2上,所有i>1000测试都成功。

>>> "12">1000
True

Fortunately this has been fixed in python 3 and it avoids those mistakes: 幸运的是,此问题已在python 3中修复,并且避免了这些错误:

>>> "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. 使用链式比较 ,这种情况下可读性强。

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. 无论使用的是Python 2还是3,这都是模棱两可的。标记了Python 3,但是在这种情况下,您应该得到TypeError而不是语义上不正确的输出。 This answer works for both versions of Python. 此答案适用于两个版本的Python。

test is a list of strings, but you want to do integer comparisons. test是一个字符串列表,但是您想进行整数比较。

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 . 请注意如何错误地打印135 ,因为它不大于1000但小于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. ...,如果您想建立一个列表,而不只是打印过滤后的元素,请创建一个空列表并append匹配项。

>>> 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. 另外,通过将内置的int映射到您一次理解内的原始列表test ,即可即时转换为int

>>> 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. 就个人而言,我更倾向于最后一种解决方案。

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 . 那是因为您正在比较一个带有integerstring ,并且如果数字不超过1000 ,例如第一个值: 135 ,如果移到elif < 135 < 2000elif

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. 假设您所有的值都是整数值。

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 首先将str转换为int然后比较您的条件

You are currently facing two problems: your numbers are not really integers , but strings , and the if condition isn't working as you expect. 您当前面临两个问题:您的数字不是真正的integers ,而是strings ,并且if条件不能按预期工作。

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: integer问题开始,您可以看到您正在处理代表数字的strings ,方法是在for循环的开始处打印它们的类型:

for i in test:
    print type(i) # string!

in python is pretty easy to convert strings into integers : 在python中将strings转换为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 (ie int("Hello World!") ), it raises an error. 在这段代码中,python将尝试将字符串转换为整数,如果他不能这样做(即int("Hello World!") ),则会引发错误。

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: 第二个问题是if条件背后的逻辑,但是幸运的是Python确实类似于英语,因此我们可以轻松地将代码翻译成口头语言:

for each number in my list, 对于我列表中的每个数字,
if the number is higher than 1000, print the number 如果数字大于1000,则打印数字
else if the number is lower than 2000, print the number 否则,如果数字小于2000,则打印数字

So now we can simulate some cases: 现在,我们可以模拟一些情况:

our number is 1337 我们的号码是1337
is the number higher than 1000? 大于1000吗? YES! 是! so - print the number 所以-打印号码

or 要么

our number is 42 我们的号码是42
is the number higher than 1000? 大于1000吗? NO! 没有! go on 继续
is the number lower than 2000? 低于2000吗? YES! 是! print the number 打印号码

and at last: 最后:

our number is 2048 我们的电话是2048
is the number higher than 1000? 大于1000吗? YES! 是! print the number 打印号码

so now the problem seems clear. 所以现在问题似乎很清楚了。
the english sentence that you want to transform into code is: 您想要转换成代码的english sentence是:

for each number in my list, if the number is higher than 1000 and the number is lower than 2000, print the number 对于列表中的每个数字,如果该数字大于1000 该数字小于2000,则打印该数字

I am not going to write you the code, but in other answers you can find it 我不会为您编写代码,但是在其他答案中您可以找到它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM