concat and append elements of array with several condition - python

Moring guys.
I have a question about how to append array elements with several condition.
assume i've array like this:
A=[[100,Z],[102,A],...,[9901,A]]
and another array like this:
B=[[100,-0.22,0.99],[102,-0.442,0.99],...,[9901,-1.22,4.99]]
The length of array A and B are different.
I want to append both the array elements with condition like this:
if(A[0][0]==B[0][0]):
temp = [B[0][1],B[0][2],A[0][1]]
array_new.append(temp)
I've try to append , and works , but the length of the new array is shorter than the A array.
Is something wrong with my code?
this is my code how I concat it:
for g in range(len(A)):
for h in range(len(B)):
if(B[h][0]==A[g][0]):
temp = [B[h][1],B[h][2],A[g][1]]
array.append(temp)
Thank you and have a nice day.

This matches the elements from A and B that have the same first entry in the list.
Convert B to a dictionary with the first element as the key.
The second elements of A are converted to characters, you can't define A recursive.
A=[[100,'Z'],[102,'A'],[9901,'C']]
B=[[100,-0.22,0.99],[102,-0.442,0.99],[9901,-1.22,4.99]]
B_Dict = { b[0]:b for b in B }
array_new = [ [B_Dict.get(a[0])[1],B_Dict.get(a[0])[2],a[1]] for a in A if B_Dict.get(a[0])]
print (array_new)

EDITED
If you indent correctly, length of array must same as A or shorter than A.
Fixing indentation:
for g in range(len(A)):
for h in range(len(B)):
if(B[h][0]==A[g][0]):
temp = [B[h][1],B[h][2],A[g][1]]
array.append(temp)

Related

How to modify list of list elements python

I have a list of lists
check = [['KH8X070.jpeg', 'ZDO9A8O.jpeg', 'ZW25RD8.jpeg', '6ZLXW92.jpeg', 'HVLA5UT.jpeg', 'A4UDC12.jpeg', '2X5KO9A.jpeg', '5HZR4VV.jpeg', '24FWS4S.jpeg'], ['Z2QC6PW.jpeg', 'EHMK14E.jpeg', 'RTV0PRH.jpeg', '71S643D.jpeg', 'KECHDQ9.jpeg', 'RU6PYPB.jpeg'], ['UG9Z4SQ.jpeg', 'H0Y3SYV.jpeg', '61HCFOK.jpeg', '14KE527.jpeg', 'XMSM050.jpeg', '5KFI2V3.jpeg', 'QSJMKUB.jpeg', 'S6TX0ZM.jpeg', '8JV3K1Y.jpeg', 'XI9OOI7.jpeg', 'JMWDOPM.jpeg'], ['0SAXG3I.jpeg', 'LA5HJNO.jpeg', 'PHHAUSA.jpeg', '900Z7S7.jpeg']]
such that I have:
check = [[0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1], [2,2,2,2,2,2,2,2,2,2,2], [3,3,3,3]]
I want to modify it such that in index list 0 of the list of list, I'll have 0's all through, in index 1 I would have 1's all through, in index 2 I'll have 2's all through and so on like that.
for i, j in enumerate(check):
checks = [...]
I know it should be a list comprehension there, but don't just know how to go about it. That's why I have come here for help.
Here's my take with an one-liner code :
>>> [map(lambda val : i, arr) for i,arr in enumerate(check)]
The above won't quite give you the result you need. But what you can do is
arr = []
for i, j in enumerate(check):
length = j
arr.append([i]*length)
This should work perfectly, I tried it out and it worked fine. Let me know how it works for you.

Appending values from one array to another array of unknown dimension

I have an array A of dimension (654 X 2). Now within a loop, I have an 'if' statement. If for a value of 'i', the condition is true, I need to append the values of 'i'th row of A into a separate array B. That means the dimension of B is not known to me beforehand. So, how to initialize such array B in python. If this is not the procedure, suggest me alternative ways to execute the same.
You could initialize B as empty array:
B = []
Then when needs, just append it with the value:
B.append( [x,y] )
you do not provide ANY code to start from, please read this to learn how to ask a question How to create a Minimal, Complete, and Verifiable example
from the almost 0 information that you've provided
you should try doing something like this:
B = []
for i in range(n):
if i % 2 == 0: # example of condition
B += [ A[i] ]
print(B)

Mistake in Python code

There is an array of integers. There are also disjoint sets, A and B, each containing integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each integer in the array, if i in A, you add 1 to your happiness. If i in B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.
Input Format
The first line contains integers n and m separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A and B respectively.
Output Format
Output a single integer, your total happiness.
Sample Input
3 2
1 5 3
3 1
5 7
Sample Output
1
Can someone please explain what is wrong with this solution? It passes some test, but fails on others.
input()
array = set(input().split())
set1 = set(input().split())
set2 = set(input().split())
res = len(set1 & array) - len(set2 & array)
print(res)
The problem is that you're transforming your inputs to sets, which in turn removes the duplicates. If you have repeated values in your input, with the set you're only adding/substracting 1 to the resulting happiness. If that's correct, your code is fine. If not, then you should work with lists rather than sets.
The code could be something like this:
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# Now we use some list comprehension to get the happiness result
res = sum([1 for elem in array if elem in list1]) - sum([1 for elem in array if elem in list2])
The first sum accumulates the positive points, and the second one the negatives. It works with multiple occurences, adding/substracting one point per each.
EDIT
A more clear approach, to understand the for loop
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# We create a variable res which will store the resulting happiness, initially 0
res = 0
# Now we iterate through the elements in array and check wheter they should add or substract
for elem in array:
# If the element is in list1, we add 1 to res
if elem in list1:
res += 1
# If the element is in list2, we substract 1 from res
elif elem in list2:
res -= 1
I took the inputs for list A and B and as a general list. I wanted to obtain happiness in 1 line using list comprehension as below. After I merged print and "happiness =" , in one line. Apparently, this is the solution to make the code faster.
input()
my_array = input().split()
listA=list(input().split())
listB=list(input().split())
print (sum(1 for data in my_array if data in listA)+sum(-1 for data in my_array if data in listB))

How to rightly locate a value at an index in nd array and save it as list in python?

I have a list called L. It has C number of elements.
I have a nd array called X. X has Boolean data (either 0 or 1). It has dimension as (20,C). There are 20 lists with each list having C number of elements
I want to locate each index that has value of 1 in X.Then I want the value at this same index in List L, and finally store this value from L in another nd array .
I write the following code
emptylist=[]
for index,value in np.ndenumerate(X): #this index is a tuple like (0,3)
tuple_to_list=list(i)
if value == 1:
emptylist.append (L[tuple_to_list[1]]) #error
the program does not stop running. Can you guide me to improve this code ?
the last line should be:
empylist.append(L[index[0]])
and I don't see what your tuple_to_list is needed for
A solution using only arrays would be the following:
L = list(np.random.rand(20)) # gives a List of radom values (to be compatible to the question)
La = np.array(L)
X = randint(0,5,(20,101)) # make an array having values from 0...4
emptylist = La[np.where(X==1)[0]] #gives those rows of L where rows of X contain 1
though the name empty is not appropriate anymore.

manipulating two 2D lists - python 2.7

if i have these two lists...
a = [[1,y,y],[2,x,x],[3,x,x],[4,y,y]
b = [[1,x,x],[4,x,x]
And i want to combine them such that a new list (c) is formed that contains each row of (a) if the first value of (a) is equal with the first value of (b)
c = [[1,y,y],[4,y,y]]
this is what i have tried so far...
for i in xrange(0,1):
for j in xrange(0,3):
if b[i][0] == a[j][0]:
c[i:] = a[[j:]
overwriting values in the c array isnt a problem due to the type of data in (a).
Im just really stuck on this, any help on whether im on the right track or if i should try something else would be greatly appreciated!
Alternatively, you can consider using sets and list comprehensions.
a = [[1,'y','y'],[2,'x','x'],[3,'x','x'],[4,'y','y']]
b = [[1,'x','x'],[4,'x','x']]
b0s = set(l[0] for l in b)
c = [l for l in a if l[0] in b0s]
print(c)
Try this:
c.append(a[j])
inside your IF statement.

Categories

Resources