列表中的特定范围(python) [英] Specific range within a list (python)
问题描述
我有一个从文本字符串中提取的整数列表,所以当我打印列表(我称之为 test
)时,我得到:
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']
并且我想打印或制作一个仅包含特定范围内的数字的新列表,例如1000-2000 之间.我尝试了以下操作,但它仍然返回原始列表中的所有项目.
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
我不明白为什么它仍然会打印低于 1000 或高于 2000 的数字.
And I can't work out why it would still be printing numbers below 1000 or above 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.
filtered_list = [x for x in ints_list if x > 1000 and x < 2000]
这篇关于列表中的特定范围(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!