This question already has answers here:
Comparing two lists using the greater than or less than operator
(3 answers)
Closed 5 years ago.
I want to compare two lists. For example:
a = [8,9,9,11]
b = [8,7,20,10]
if a >= b :
print "true"
Why does this print "true"? I want to compare the values vertically like this:
8 >= 8 is true
9 >= 7 is true
9 >= 20 is false but the program return true
11 >= 10 is true
You can use list comprehension and all function as follows:
code:
a = 8,9,9,11
b = 8,7,20,10
print all([(a > b) for a, b in zip(a,b)])
output:
False
You can use a list comprehension for comparing two lists element wise then use all function to check all of comparison are True:
a = [8,9,9,11]
b = [8,7,20,10]
all(a[i]>=b[i] for i in range(len(a))) # False
Related
This question already has answers here:
Fastest way to check if a value exists in a list
(11 answers)
Closed 1 year ago.
I have a long list of values and want a list comprehension to evaluate to True (and print "True" only once if any value in the list is the integer 1).
I can print "True" for each instance a 1 is found but cannot see how to just have it return a single True.
Code
a = [0,0,1,1,0,1]
b = [print("True") for i in a if i == 1]
print('\n')
#c = [print("True") if any i in a is True] # doesn't work, syntax error
d = [print("TRUE") if any(i == 1)]
Did you mean to convert the resulting list to bool()?
a = [0,0,1,1,0,1]
b = bool([i for i in a if i == 1])
print(b)
if your list only contains zeros and ones you could just print(any(a))
otherwise you could do this
a = [0,0,1,0,2,0]
b =[x==1 for x in a]
print(any(b))
returns True
This question already has answers here:
Python: See if one set contains another entirely? [duplicate]
(7 answers)
Closed 2 years ago.
I have 2 elements for example 1 and 2.
I need to find out if both of these elements are in my array.
For example:
I have 1,2,3,4. And i have Array [2,3,4,111].
If all my elements are in the array, then it's True, else False
array = [2,3,4,111]
elements_to_check = [2,3]
result = set(elements_to_check).issubset(array)
print(result)
Prints True if elements_to_check = [2,3]
Prints False if elements_to_check e.g. = [2,3,5]
Another solution would be
list = [2,3,4,111]
elements_to_check = [1,2]
result = len([x for x in elements_to_check if x in list]) == len(elements_to_check)
Prints True if elements_to_check = [2,3]
Prints False if elements_to_check e.g. = [1,2]
This question already has answers here:
Multiple If/else in list comprehension in Python
(4 answers)
Closed 3 years ago.
I am trying to translate this for loop into a list comprehension:
a = [1,2,3,4,5,6,7,8,9]
result = []
for i in a:
if i <= 3:
result.append(1)
elif i > 4 and i < 7:
result.append(2)
and I have tried this
[1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]
which complains about
File "<ipython-input-155-eebf07a9e0d8>", line 2
[1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]
^
SyntaxError: invalid syntax
List comprehension:
Add some more conditions :D (no this is really messy)
[
1 if i <= 3 else 2
for i in a
if i != 4 and i < 7
]
How did we get here?
Basic list comp: [EXPRESSION for TARGET in ITERABLE if CONDITION]
Ternary expression: (IF_TRUE if CONDITION else IF_FALSE)
Get the for loop in. Simple enough for i in a.
Add conditions that filter out items which will be ignored. Once it gets past CONDITION, there has to be an item in the list at that position. In this case, we don't want i if it's 4 or greater than 7. if i != 4 and i < 7.
Do what you need with the item. In this case, we want 1 if i is smaller or equal to 4. Otherwise, we'll take 2. 1 if i <= 3 else 2. Note: this is a ternary expression. Check them out!
This question already has answers here:
Is python's "set" stable?
(7 answers)
Closed 4 years ago.
I have a following exemplary setup in Python:
a = list(frozenset(['haha', 'lol']))
b = list(frozenset(['lol', 'haha']))
Does
a == b
always return True?
Is it possible that the list of frozenset of the same elements can return False with the above setup?
The equivalence semantics between (frozen)sets are that if they contain equivalent items they are equivalent. Sets do not have order.
But, since lists have order, the cast to list can potentially cause them to not be equivalent (depends on the order of iteration over the (frozen)set - which is an implementation detail).
Here is an example of a collision in the internal implementation that causes a different iteration order due to the instertion order (this is in CPython implementation):
>>> a = list(frozenset([1, 9]))
>>> b = list(frozenset([9, 1]))
>>> a == b
False
Example with strings:
First we need to find a collision (I will not go into details):
>>> hash('1') % 8
0
>>> hash('2') % 8
5
>>> hash('3') % 8
2
>>> hash('4') % 8
3
>>> hash('5') % 8
1
>>> hash('6') % 8
4
>>> hash('7') % 8
5 # same as '2' ! Found!
Now we need to add in different order to the set to cause a re-hash (again, not going into details):
>>> s1, s2 = '2', '7'
>>> a = list(frozenset([s1, s2]))
>>> b = list(frozenset([s2, s1]))
>>> a == b
False
This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
Closed 3 months ago.
I am receiving the count of each line in each list,
I am looking to sum each particular values of entire list, (Nested lists included)
[[3],[4],][1],[3]] = * 11 is my desired result.
example: code
ar1 = [
['jam','apple','pear'],
['toes','tail','pinky','liar'],
['aha!'],
['jam','apple','pear']
]
def function(arg1)
heads = 0
for i in arg1:
heads += arg1.count(i)
print heads
I have used this print because i dont know how to compile and debug any other for than the print statement and recheck work, so please no flaming.(newbie alert)
example: result
['jam','apple','pear'] 1
['toes','tail','pinky','liar'] 2
['aha!'] 3
['jam','apple','pear'] 4
I prefer a hint, or hints to what methods i should be applying or an example. I am in no way expecting a solution. I
You have some choices :
1.flatten your nested list and calculate the length of total list:
>>> len(reduce(lambda x,y:x+y,ar1))
11
Or you can loop over your list and sum the length of all your sub-lists you can do it with a generator expression within sum function :
>>> sum(len(i) for i in ar1)
11
In case your actual data contains deeper nesting than you've shown:
def sum_len(lst):
return sum(1 if not isinstance(e, list) else sum_len(e) for e in lst)
ar1 = [
['jam','apple','pear'],
['toes','tail','pinky','liar'],
['aha!'],
['jam','apple','pear']
]
print sum_len(ar1) # 11
# Same elements, with arbitrary list wrapping:
ar2 = [
[['jam','apple',['pear']]],
[['toes',['tail','pinky'],'liar']],
[['aha!']],
[[['jam','apple'],'pear']]
]
print sum_len(ar2) # 11