Python: Use a Loop to Manipulate Arrays [duplicate] - python

This question already has answers here:
Extract first item of each sublist
(8 answers)
Closed 4 years ago.
I have to perform the same operation on a number of arrays. Is there a way to use a loop in Python to carry out this repetitive task?
For example, I have 5 arrays: A, B, C, D, and E.
I want to carry out the following:
A = A[0]
B = B[0]
C = C[0]
D = D[0]
E = E[0]
Is there any way to do this using a loop or some other technique to avoid typing almost the same thing multiple times?
My question has been marked as a duplicate of this question. There, the person is asking how to extract the first element from each list (or in my case array). I am not simply trying to extract the first element. I actually want to replace each array with it's first element -- literally A = A[0].
Some are saying this is not a good idea, but this is actually what I want to do. To give some context, I have code that leaves me with a number of 2D arrays, with shapes n x m. When n = 1, the first dimension is irrelevant, and I would like to dispense with that dimension, which is what A = A[0] does. My code needs to handle both cases where n = 1 and cases when n > 1.
In other words, when n = 1, my code results in an array A that is of the following form: A = array([[a]]), and I want to change it so that A = array([a]). And to reiterate, I need the flexibility of allowing n > 1, in which case A = array([[a1],[a2],...]). In that case, my code will not execute A = A[0].
The solution by Mark White below works, if you change the last line to:
A,B,C,D,E = [x[0] for x in [A,B,C,D,E]]
What's interesting is that this solution makes the code more compact, but actually involves as many characters as (an technically more than) the brute force approach.

I do think it is a pretty easy problem ,in my case ,I use three array ,but I think you can do five , my dear friend!
A = [1,3,4]
B = [2,4,5]
C = [54,5,6]
A,B,C = [x[0] for x in [A,B,C]]

Simply create a list of lists (or, specifically, references to A, B, C, etc.)
l = [A, B, C, D, E]
Then, you can iterate over l however you choose.
for i in range(len(l)):
l[i] = l[i][0]
Note that this will update l[i] rather than the lists (A, B, C, ...) themselves.

Related

List Problem in python to sort a list of string without using sort or sorted function

I am stuck in this list problem, I am unable to solve it.
list1= ["aaditya-2", "rahul-9", "shubhangi-4"]
I need to sort this list without using sort/sorted function.... and also it should sort on the basis of numbers at the last..
Output:
["aaditya-2", "shubhangi-4", "rahul-9"]
OR
["rahul-9", "shubhangi-4", "aaditya-2" ]
You could try something like this:
def sort_arr(arr, function):
arr2 = [function(i) for i in arr] # apply your function to all the elements in the array, in this case it is get the last digit
for i in range(1, len(arr2)): # begin looping from the first index of the array to the last index
k = arr2[i] # assign the value of the ith item to a variable
j = i - 1 # keep track of the index begin considered
while j >= 0 and k < arr2[j]: # while k is less than the item before it, do
arr2[j + 1] = arr2[j] # shift the ith value one step to the front of the array
j -= 1
arr2[j + 1] = k # once the correct position has been found, position arr2[i] at its correct location
return arr2 # return sorted array
print(sort_arr(list1, lambda x: int(x[-1]))) # the lambda gets the last digit and turns it into an integer
Learn more about lambda's here.
This is an implementation of insertion sort. Learn more about it here.
Hope this helps!
EDIT: Just realized this did not directly answer OP's question. Updated answer to match.
As I understand it, it's a question of ordering. I don't think this is about implementing a sorting algorithm. Here I define a order function that works on two strings and orders them by last character. This is applied 3 times to sort 3-element list.
def order(a, b):
return (b, a) if a[-1] > b[-1] else (a, b)
list1 = ["aaditya-2", "rahul-9", "shubhangi-4"]
a, b, c = list1
a, b = order(a, b)
a, c = order(a, c)
b, c = order(b, c)
list1 = [a, b, c] # ["aaditya-2", "shubhangi-4", "rahul-9"]
For reverse sort, just use < in the order function.

Why Python can achieve a, b = b, a [duplicate]

This question already has an answer here:
How does swapping of members in tuples (a,b)=(b,a) work internally?
(1 answer)
Closed 1 year ago.
If we need to swap variables a and b in C or Java, we need to have something (pseudo code) like:
tmp = a;
a = b;
b = tmp;
Why Python can do it by a, b = b, a. What happened with it?
Not sure whether it is the right place for this question. But I do appreciate it if someone could give me some clues.
It's because python provides a special "tuple unpacking" syntax that many other languages don't have. I'll break apart what's going on:
The b, a on the right of the equals is making a tuple (remember, a tuple is pretty much the same as a list, except you can't modify it). The a, b on the left is a different syntax that's unpacking the tuple, i.e. it takes the first item in the tuple, and store it in the first variable listed, then it takes the second item and stored it in the second variable, and so forth.
This is what it looks like broken up in multiple steps:
a = 2
b = 3
my_tuple = a, b
print(my_tuple) # (2, 3)
b, a = my_tuple
print(a) # 3
print(b) # 2
And here's another, simpler examples of tuple unpacking, just to help wrap your mind around it:
x, y, z = (1, 2, 3)
print(x) # 1
print(y) # 2
print(z) # 3
By the way, Python's not the only one, Javascript can do it too, but with arrays:
[a, b] = [b, a];

How to zip two sequences (one shifted by N elements)? [duplicate]

This question already has answers here:
How to iterate through two lists with one of them shifted?
(3 answers)
Closed 2 years ago.
I have two lists A and B and I want to traverse pairs of elements (A[0], B[2]), (A[1], B[3]), etc.
Without the shift I could just use zip(A, B) to do it efficently.
In this example the shift is 2 but may happen that I will need a shift of N. How to do it efficiently (not indexing into two lists)?
I think a concise way to do this would be
zipped = zip(list1, list2[n:])
Where n is an integer representing the offset.
Eventually, I arrived at the following generic function:
def zip_shift(s1, s2, shift, placeholder):
i1 = iter(s1)
i2 = iter(s2)
while shift > 0:
yield placeholder, next(i2) # leave only next(i2) if no placeholder pairs are needed
shift -= 1
yield from zip(i1, i2) # or return zip
The above function works like a generator that first fills in the placeholder values shift times instead of taking values from the second sequence s2. Afterward, it works just like zip. The yield from is a relatively new construct (since Python 3.3). There are subtle differences between yield from and return above but can be neglected in this situation.
Of course if the shift value is 1 almost (with the exception of the pairs with the placeholder) the same can be achieved with:
zip(s1, next(s2))
As with zip sequences do not have to be of the same length. The generator works as long as the shorter sequence is not exhausted.

How to create a function that uses 2 integers from 2 different lists and adding the pair to a certain integer?

Doing some basic python coding. Here is the problem I was presented.
Create a function that takes 3 inputs:
Two lists of integers
one integer n
Prints the pairs of integers, one from the first input list and the other form the second list, that adds up to n. Each pair should be printed.
Final Result (Example):
pair([2,3,4], [5,7,9,12], 9)
2 7
4 5
I'm still awfully new to Python, studying for a test and for some reason this one keeps giving me some trouble. This is an intro course so basic coding is preferred. I probably won't understand most advanced coding.
The simplest naieve approach would be to just test all possible combinations to see if they add up.
def pair(list1, list2, x):
for a in list1:
for b in list2:
if a + b == x:
print a, b
There are more efficient ways to do it (eg. ignore duplicates, ignore numbers greater than x, etc.)
If you wanted to do it in a single loop, python has some convenience functions for that
from itertools import product
for a, b in product(list1, list2):
if a + b == x:
print a, b

python function changing list values

I'm trying to call a function recursively, and passing parts of the list to the function.
def op3(c,i):
d = []
for l in range(0,len(c),+1):
d.append(c[l])
a, b = [], []
if len(d)>=3:
for l in range(1,len(d)-1,+1):
a.append(d[l])
for l in range(2,len(d),+1):
b.append(d[l])
A,B = [],[]
for j in range(0,len(a),+1):
a[j][i] = a[j][i]+a[j][i+1]
a[j].pop(i+1)
insertf(a,final)
A.append(a[j])
op3(A,i+1)
for k in range(0,len(b),+1):
b[k][i+1] = b[k][i+1]+b[k][i+2]
b[k].pop(i+2)
insertf(b,final)
B.append(b[k])
op3(B,i+1)
but the values in the original list are changed in list 'b' to the new values of d after the first nested 'for' loop runs.
i'm fairly new to python. i have read that this is just how lists work in python. is there a way around this?
All the modified C-style for loops make my head hurt. Trying to parse...
def op3(c,i):
d = c[:]
if len(d)>=3:
a=d[1:-1]
b=d[2:]
#A,B=[],[]
for item in a:
item[i] += item.pop(i+1)
insertf(a,final) # Totally unknown behaviour, does this modify a?
#A.append(item) # Seems pointless, A ends up a copy of a, and op3
# # does not modify c (only its items)
op3(a,i+1)
for item in b:
item[i+1] += item.pop(i+2)
insertf(b,final)
op3(b,i+1)
So from what the code does, it expects a list of lists, and it modifies the inner lists. It also calls itself recursively in a manner that seems to have no stop condition, but will break if the inner lists run out any((len(ci)<=i+2 for ci in c)).
On the whole, I'd say we can't provide a good answer because this code fragment just doesn't express what you want done. It seems likely the key point here is that lists are not two-dimensional; every list a[j] or b[k] is an independent object (though a[j] is b[j-1] since you extract them from the same list c), and has no knowledge of the manipulations you do on a,b,c,d,A,B.
Could you please describe what data structures you have and expect, and what sort of processing you're trying to do? It feels a bit like it would fit in about one expression of numpy.

Categories