Return list of items in list greater than some value
You can use a list comprehension to filter it:
j2 = [i for i in j if i >= 5]
If you actually want it sorted like your example was, you can use sorted:j2 = sorted(i for i in j if i >= 5)
Or call sort
on the final list:j2 = [i for i in j if i >= 5]
j2.sort()
Check if all values in list are greater than a certain number
Use the all()
function with a generator expression:
>>> my_list1 = [30, 34, 56]
>>> my_list2 = [29, 500, 43]
>>> all(i >= 30 for i in my_list1)
True
>>> all(i >= 30 for i in my_list2)
False
Note that this tests for greater than or equal to 30, otherwise my_list1
would not pass the test either.If you wanted to do this in a function, you'd use:
def all_30_or_up(ls):
for i in ls:
if i < 30:
return False
return True
e.g. as soon as you find a value that proves that there is a value below 30, you return False
, and return True
if you found no evidence to the contrary.Similarly, you can use the any()
function to test if at least 1 value matches the condition.
number of values in a list greater than a certain number
You could do something like this:
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3
It might initially seem strange to add True
to True
this way, but I don't think it's unpythonic; after all, bool
is a subclass of int
in all versions since 2.3:>>> issubclass(bool, int)
True
Finding list indexes of numbers greater than a value
You can simply iterate through the list and break when you condition is true:
test_list = [1,5,7,11,20,26,89]
for i, value in enumerate(test_list):
if value > 13:
break
print(value) # 20
print(i) # 4
Python remove elements that are greater than a threshold from a list
Try using a list comprehension:
>>> a = [1,9,2,10,3,6]
>>> [x for x in a if x <= 5]
[1, 2, 3]
This says, "make a new list of x values where x comes from a but only if x is less than or equal to the threshold 5.The issue with the enumerate() and pop() approach is that it mutates the list while iterating over it -- somewhat akin to sawing-off a tree limb while your still sitting on the limb. So when (i, x)
is (1, 9)
, the pop(i) changes a to [1,2,10,3,6]
, but then iteration advances to (2, 10)
meaning that the value 2 never gets examined. It falls apart from there.
FWIW, if you need to mutable the list in-place, just reassign it with a slice:
a[:] = [x for x in a if x <= 5]
Hope this helps :-) Finding if a value in a list is greater than the item below it
This is your existing code:
def funcc(refl):
if (refl[0]) > (refl[1]):
print("more")
else:
print("less")
Your problem is, you only compare the first (refl[0]
) and second (refl[1]
) elements. A trivial fix would be:def funcc(refl):
for i in range(len(refl)) - 1:
if (refl[i + 1]) >= (refl[i]):
return False
return True
then use it as follows:refl = ["100", "99", "90", "80", "60", "50", "10"]
if funcc(refl):
print("Monotone decreasing")
else:
print("Not monotone decreasing")
First Python list index greater than x?
next(x[0] for x in enumerate(L) if x[1] > 0.7)
Find the indices of elements greater than x
OK, I understand what you mean and a Single line of Python will be enough:
using list comprehension
[ j for (i,j) in zip(a,x) if i >= 4 ]
# a will be the list compare to 4
# x another list with same length
Explanation:
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j']
Zip function will return a list of tuples>>> zip(a,x)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]
List comprehension is a shortcut to loop an element over list which after "in", and evaluate the element with expression, then return the result to a list, also you can add condition on which result you want to return>>> [expression(element) for **element** in **list** if condition ]
This code does nothing but return all pairs that zipped up.>>> [(i,j) for (i,j) in zip(a,x)]
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]
What we do is to add a condition on it by specify "if" follow by a boolean expression>>> [(i,j) for (i,j) in zip(a,x) if i >= 4]
[(4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]
using Itertools>>> [ _ for _ in itertools.compress(d, map(lambda x: x>=4,a)) ]
# a will be the list compare to 4
# d another list with same length
Use itertools.compress with single line in Python to finish close this task>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j'] # another list with same length
>>> map(lambda x: x>=4, a) # this will return a boolean list
[False, False, False, True, True, True, True, True, True]
>>> import itertools
>>> itertools.compress(d, map(lambda x: x>4, a)) # magic here !
<itertools.compress object at 0xa1a764c> # compress will match pair from list a and the boolean list, if item in boolean list is true, then item in list a will be remain ,else will be dropped
#below single line is enough to solve your problem
>>> [ _ for _ in itertools.compress(d, map(lambda x: x>=4,a)) ] # iterate the result.
['d', 'e', 'f', 'g', 'h', 'j']
Explanation for itertools.compress, I think this will be clear for your understanding:>>> [ _ for _ in itertools.compress([1,2,3,4,5],[False,True,True,False,True]) ]
[2, 3, 5]
Related Topics
Pairwise Crossproduct in Python
Cheap Way to Search a Large Text File for a String
Plotting Results of Hierarchical Clustering Ontop of a Matrix of Data in Python
Broken References in Virtualenvs
Running Multiple Bash Commands with Subprocess
How Dangerous Is Setting Self._Class_ to Something Else
Range Over Character in Python
How to Wrap a String in a File in Python
How to Ignore Hidden Files Using Os.Listdir()
Apt Command Line Interface-Like Yes/No Input
Pandas - Filter Dataframe by Another Dataframe by Row Elements
Pip Is Not Able to Install Packages Correctly: Permission Denied Error
How to Fix Selenium Webdriverexception: the Browser Appears to Have Exited Before We Could Connect
Is There a Function to Determine Which Quarter of the Year a Date Is In
How to Get a Gcp Bearer Token Programmatically with Python
Row-Wise Average for a Subset of Columns with Missing Values