manipulating two 2D lists - python 2.7 - python

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.

Related

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)

How to calculate numbers in a list [duplicate]

This question already has answers here:
Python: Finding differences between elements of a list
(12 answers)
Difference between consecutive elements in list [duplicate]
(3 answers)
Closed 4 years ago.
here is my code.
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]
B = []
i = 0
for i in range(len(A)):
c = A[i]-A[i-1]
B.append(c)
print(c)
I want to get the differences between two continuous numbers in this list, eg,(85.25496701-86.14803712). So in the results, I should have eight numbers as results.
But the results I get are:
-0.9337014900000042
-0.8930701099999965
1.2483756999999969
-0.4766759099999973
0.5878891400000015
0.2898961899999932
-0.24925897999999336
0.4459744699999959
-0.019429009999996083
I don't need -0.9337014900000042 since it comes from the first number subtract the last number in the list. What should I do the fix it? Thanks
That's the strength and the weakness of python: index -1 is always valid when the list isn't empty, which can lead to programs not crashing but not doing what you want.
For those operations, it's better to use zip to interleave the list with a sliced version of itself without the first number:
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]
diffs = [ac-ap for ac,ap in zip(A[1:],A)]
or with itertools.islice to avoid creating a new list to iterate on it:
import itertools
diffs = [ac-ap for ac,ap in zip(itertools.islice(A,1,None),A)]
result (8 values):
[-0.8930701099999965, 1.2483756999999969, -0.4766759099999973, 0.5878891400000015, 0.2898961899999932, -0.24925897999999336, 0.4459744699999959, -0.019429009999996083]
It's possible to do this in base Python, but you might like the semantic clarity of Pandas:
import pandas as pd
pd.Series(A).diff().values[1:]
array([-0.89307011, 1.2483757 , -0.47667591, 0.58788914, 0.28989619,
-0.24925898, 0.44597447, -0.01942901])
You can just do:
B = [x-y for x, y in zip(A[1:], A)]
print(B) # -> [-0.8930701099999965, 1.2483756999999969, -0.4766759099999973, 0.5878891400000015, 0.2898961899999932, -0.24925897999999336, 0.4459744699999959, -0.019429009999996083]
You need to make sure you star from a correct index. In your current code, in the first iteration of the loop you will be computing A[0] - A[-1]. Hence, you need to start i from 1 to ensure in the first iteration you compute the value of A[1] - A[0]. The corrected version of your code is here:
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861]
B = []
i = 0
for i in range(1, len(A)):
c = A[i]-A[i-1]
B.append(c)
print(c)
I think the problem is that the loop subtracts the first element to the last because the loop starts at index 0 and subtracts it from index -1 (python takes -1 as the last index of a list). A better solution imo would be:
A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594,
86.90445213, 86.65519315, 87.10116762, 87.08173861]
B = []
i = 0
for i in range(len(A)-1):
c = -(A[i]-A[i+1])
B.append(c)
print(c)
The easiest would be:
result = [x-y for x,y in zip(A[1:], A[:-1])]

Input in a cycle (Python)

I'm learning Python as my first language and now I trying to resolve this problem:
I have to make a loop where I ask the user which elements from a list they want to remove and then remove the elements selected. The loop stops only when the user insert a specific number that corresponds to the length of the list increased by 1 (so I won't have any problem).
I have another problem related to this:
elements_list = ['a','b','c','d']
length_list = len(elements_list)
for i in range(0, length_list):
print (str(i) + str(')') + elements_list[i])
This will print the list starting with 0:
0) a
1) b
2) c
3) d
What do I have to do if I want the list start with 1? (if I use 1 instead of 0 in the range it doesn't print the first element of the list)
In Python, lists can be iterated directly, and enumerate is used to generate indexes. Its optional second parameter gives a starting number:
>>> elements = ['a','b','c','d']
>>> for i,v in enumerate(elements,1):
... print('{}) {}'.format(i,v))
...
1) a
2) b
3) c
4) d
If using Python 3.6+, formatting output is even more simple using f-strings:
>>> elements = ['a','b','c','d']
>>> for i,v in enumerate(elements,1):
... print(f'{i}) {v}')
...
1) a
2) b
3) c
4) d
Refs:
enumerate
str.format
Formatted string literals
One way would be to add a 1 in the range, then subtract a 1 from the index
elements_list=['a','b','c','d']
lenght_list=len(elements_list)
for i in range(1, lenght_list+1):
print (str(i) + str(')') + elements_list[i-1])
Edit: TheoretiCAL's approach is even more straight forward, simply adding 1 to the print statement achieves the same thing.

Updating a list in a loop in python without using the append function.

Hi there suppose I have;
a = np.array([1.,2.])
b = np.array([3.,4.])
r = []
...
for i in range(10)
b*i
r[i] = ((a[0]+b[0]) - (a[1] - b[1]))
...
i = i+1
The code is meant to take arrays a and b and perform addition and subtraction on elements from them, and place them into what I think should be a list, which in this case I've called r. (i.e so r[0] = 0, r[1] = 6 etc.)
I know this does not work, but I don't know why can someone tell me what I should define 'r' to be?
I'd rather avoid using something like;
r.append(...)
The end goal is to plot r vs i , should I therefore construct both lists and then plot them against eachother, or should I include it in the loop somehow.
Thanks in advance!
Use list comprehensions, as an example, I'm going to rewrite your whole for loop and r = [] into this:
r = [((a[0]+(b*i)[0]) - (a[1] - (b*i)[1])) for i in range(1,10)]
This does the same, more readable, much more faster.

Wrong output in Python - as per my logic

Can someone tell me why my program is working weird. I am trying to sort list1 in ascending order. This code is part of my quick sort program I am trying to write. As per my logic which I am applying in this code, and I checked manually too, the output should be [1,2,3,4,5]. However the output is coming out to be [1,2,2,4,5]. Can you tell what's going wrong?
list1=[3,2,1,5,4]
n_list1=len(list1)
count=0
for position1, item1 in enumerate(list1[0:n_list1]):
temp=item1
count=count+1
for position2 in range(count,n_list1):
if list1[position1]>list1[position2]:
list1[position1]=list1[position2]
list1[position2]=temp
temp=list1[position1]
print list1
EDIT: What I am trying to do is like this:
I start comparing the first element with the following (n-1) elements and swap the smallest element with the first one. Now I go to 2nd element and compare it with the following (n-2) elements and swap with the smallest element among those (n-2) elements. Like this I move forward.
Note: This is part of my quicksort program and it is not in itself quicksort. This part is for the list1 to which I assign numbers less than pivot. Another code will be for list2 where I will assign numbers greater than pivot.
Since you do count = count + 1 right before the innermost for, you never get to reach the first position of list1 (list1[0]), which is the element "3".
[Edit] Looking more carefully at your code, there seems to be a lot of confusion. For instance, on
list1[position1]=list1[position2]
list1[position2]=temp
temp=list1[position1]
You're losing list1[position1]: you're overwriting it with list[position2], before trying to save it at the temp variable. Try moving temp=list1[position1] to the first line after the if.
And, honestly, your implementation is overly complicated. I suggest you try writing it in pseudo-code, try to actually understand what's going on, and then re-implement it.
The answer provided by rbp is absolutely correct!
Also, I guess you could simplify the above by remove count itself, also directly enumerate the list and use the python idiom - a, b = b, a to swap the values
list1=[3,2,1,6,5,4]
n_list1 = len(list1)
for position1, item1 in enumerate(list1):
for position2 in range(position1,n_list1):
if list1[position1]>list1[position2]:
list1[position1] , list1[position2] = list1[position2], list1[position1]
print list1
Output:
[1, 2, 3, 4, 5, 6]
[Edit: About the idiom]
>>> a = 4
>>> b = 5
>>> a , b = b, a
>>> a
5
>>> b
4
>>> c = 5
>>> d = 6
>>> t = c
>>> c = d
>>> d = t
>>> c
6
>>> d
5
>>>
A small improvement to pyfunc's correct answer...
This line
for position2 in range(position1,n_list1)
can be
for position2 in range(position1+1,n_list1)
and will save you a little time.

Categories

Resources