Related
So lets say I have two lists a=[1,2,3,4,5,6] and b=[2,34,5,67,5,6] I want to create a third list which will have 1 where elements are different in a and b and 0 when they are same, so above would be like c=[1,1,1,1,0,0]
You can zip the lists and compare them in a list comprehension. This takes advantage of the fact that booleans are equivalent to 1 and 0 in python:
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
[int(m!=n) for m, n, in zip(a, b)]
# [1, 1, 1, 1, 0, 0]
Try a list comprehension over elements of each pair of items in the list with zip:
[ 0 if i == j else 1 for i,j in zip(a,b) ]
Iterating with a for loop is an option, though list comprehension may be more efficient.
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
c=[]
for i in range(len(a)):
if a[i] == b[i]:
c.append(0)
else:
c.append(1)
print(c)
prints
[1, 1, 1, 1, 0, 0]
If you will have multiple vector operations and they should be fast. Checkout numpy.
import numpy as np
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
a = np.array(a)
b = np.array(b)
c = (a != b).astype(int)
# array([1, 1, 1, 1, 0, 0])
idk if this is exactly what youre loocking for but this should work:
edidt: just found out that Joe Thor commented almost the exact same a few minutes earlier than me lmao
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5, 6]
results = []
for f in range(0, len(a)):
if a[f] == b[f]:
results.append(0)
else:
results.append(1)
print(results)
This can be done fairly simply using a for loop. It does assume that both lists, a and b, are the same length. An example code would like something like this:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
for i in range(0,len(a)):
if(a[i] != b[i]):
c.append(1)
else:
c.append(0)
This can also be done using list comprehension:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
c = [int(i != j) for i,j in zip(a,b)]
The list comprehension code is from this thread: Comparing values in two lists in Python
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5,6]
c = []
index = 0
x = 1
y = 0
for i in range(len(a)): # iterating loop from index 0 till the last
if a[index]!= b[index]: # comapring each index
c.append(x) # if not equal append c with '1'
index += 1 # increment index to move to next index in both lists
else:
c.append(y)
index += 1
print(c)
This should work for two lists of any type.
tstlist = ["w","s","u"]
lstseasons = ["s","u","a","w"]
lstbool_Seasons = [1 if ele in tstlist else 0 for ele in lstseasons]
Output: lstbool_Seasons = [1,1,0,1]
This is the first time I have posted anything, still figuring out how things work here, so please forgive faux pas...
Here is the code I have got so far. Now output is [1, 3, 5, 7, 9]
N = 10
for i in range(1, 10):
arr.append(i)
arr2 = []
f = lambda x: x ** 2
arr2 = filter(lambda x: x % 2 != 0, arr)
map(lambda x: x ** 2, arr2)
print(list(arr2))```
Your last for-loop applies the lambda function to the elements in your list, but does not save the result.
Try:
a = [i for i in range(1,10)]
a2 = filter(lambda x: x % 2 != 0, a)
a3 = map(lambda x: x**2, a2) # This is a generator object
final_list = list(a3) # This is a list
Python Tips on map filter reduce
You are discarding the result of f(i) as soon as you create it. You need to append it to some list (also, no need to consume the filter object into a list):
result = []
for i in arr2:
result.append(f(i))
Please note that binding a lambda to an identifier is discouraged in accordance with PEP 8.
The best way to solve this problem is without list comprehensions is a combination of filter and map like so:
arr2 = list(map(lambda x: x ** 2, filter(lambda x: x % 2 != 0, arr)))
Here's a very slightly modified version:
arr = []
N = 10
for i in range(1, N):
arr.append(i)
arr2 = []
f = lambda x: x ** 2
arr2 = filter(lambda x: x % 2 != 0, arr)
for i in list(arr2):
print(f(i))
arr2 isn't a list. It's an iterator, which you can only convert to a list once.
Here's a more compact version:
N = 10
arr = range(1, N)
square = lambda x: x ** 2
keep_odd = lambda x: x % 2 != 0
arr2 = list(filter(keep_odd, arr))
for i in arr2:
print(square(i))
print(arr2)
It outputs:
1
9
25
49
81
[1, 3, 5, 7, 9]
You aren't saving the value in the array, you are just printing it.
N = 10
for i in range(1, 10):
arr.append(i)
result = []
f = lambda x: x ** 2
arr2 = filter(lambda x: x % 2 != 0, arr)
for i in arr2:
result.append(f(i))
print(result)
lst = [1, 2, 3]
ans = list(map(lambda x: x ** 2, filter(lambda x: x % 2 != 0, lst)))
print(ans)
I am using Python 3, my question is why is the output different?
print([x * x for x in range(2, 5, 2) if x % 4 == 0]) # returns [16]
q = [x * x for x in range(2, 5, 2)]
print(list(filter(lambda x: x % 4 == 0, q))) # returns [4, 16]
print(([x * x for x in range(2, 5, 2) if x % 4 == 0]))
here, range evaluates to [2,4] and only [4] is able to get past the if condition
q = ([x * x for x in range(2, 5, 2)])
print(list(filter(lambda x: x % 4 == 0, q)))
here, q contains x*x of each element, hence the list is [2*2, 4*4] = [4, 16], and both elements get past filter selector
Because q contains squares
In [2]: q
Out[2]: [4, 16]
and lambda x: x % 4 == 0 will return True for both of them:
In [3]: 4 % 4 == 0
Out[3]: True
In [4]: 16 % 4 == 0
Out[4]: True
The list comprehension squares numbers after performing the check, which fails for 2 (2 % 4 is 2):
In [5]: 2 % 4 == 0
Out[5]: False
Therefore, 2 * 2 = 4 won't be included in the list.
In short, if you want to get the same behaviour, modify your list comprehension to square numbers before computing the remainder:
[x * x for x in range(2, 5, 2) if pow(x, 2, 4) == 0] # [4, 16]
# ↖ equivalent to (x ** 2) % 4
In the former, each item in [2,4] is checked against x % 4 == 0. In the latter, filter applies the lambda to each item in q, which is not [2,4], but rather [4,16]. Hence, x % 4 == 0 returns true twice.
I would like to add some integer to a range of items in a list in python.
I know that this is correct if you want to add an integer to every item in a list:
A = 2
B = 5
C = 6
mylist = [1,2,3,4,5,6,7,8]
mylist[:] = [i+C for i in mylist]
print mylist
but I would like to add C to items A through B. so that instead of resulting in this list:
mylist = [7,8,9,10,11,12,13,14]
I would get this list:
mylist = [1,2,*9*,*10*,*11*,*12*,7,8]
is there a way to do this?
Thanks
Assign to a slice of the list:
>>> A = 2
>>> B = 5
>>> C = 6
>>> mylist = [1,2,3,4,5,6,7,8]
>>> mylist[A:B+1] = [i+C for i in mylist[A:B+1]]
>>> mylist
[1, 2, 9, 10, 11, 12, 7, 8]
>>>
for i in range(A, B+1):
mylist[i] += C
In addition to #iCodez answer, if you don't want to modify the original, you can use if-else
A = 2
B = 5
C = 6
oldlist = [1,2,3,4,5,6,7,8]
mylist = [x+C if A <= i <= B else x for i, x in enumerate(oldlist)]
mylist[A:B+1] = [i+C for i in mylist[A:B+1]]
folks,
I want to modify list element with list comprehension. For example, if the element is negative, add 4 to it.
Thus the list
a = [1, -2 , 2]
will be converted to
a = [1, 2, 2]
The following code works, but i am wondering if there is a better way to do it?
Thanks.
for i in range(len(a)):
if a[i]<0:
a[i] += 4
a = [b + 4 if b < 0 else b for b in a]
If you want to change the list in-place, this is almost the best way. List comprehension will create a new list. You could also use enumerate, and assignment must be done to a[i]:
for i, x in enumerate(a):
if x < 0:
a[i] = x + 4
This version is older, it would work on Python 2.4
>>> [x < 0 and x + 4 or x for x in [1, -2, 2]]
0: [1, 2, 2]
For newer versions of Python use conditional expressions as in Adam Wagner or BenH answers
Try this:
b = [x + 4 if x < 0 else x for x in a]
Or if you like map more than a list comprehension:
b = map(lambda x: x + 4 if x < 0 else x, a)
Why mutate, when you can just return a new list that looks like you want it to?
[4 + x if x < 0 else x for x in [1, -2, 2]]