How to shift the rows in python array? [duplicate] - python

This question already has answers here:
Efficient way to rotate a list in python
(27 answers)
Closed 5 days ago.
I'm trying to find a simple way to shift the position of raw in python array.
And here is my four array
list1 = ['0x68', '0x65', '0x6c', '0x6c']
list2 = ['0x20', '0x68', '0x69', '0x74']
list3 = ['0x6c', '0x65', '0x72', '0x68']
list4 = ['0x65', '0x6c', '0x6c', '0x20']
It will be nice if I can make a function for shift it. For example I might shift it like this
swaps the row elements among each other. It skips the first row. It shifts the elements in the second row, one position to the left. It also shifts the elements from the third row two consecutive positions to the left, and it shifts the last row three positions to the left.

they are 4 separate lists so I would iterate trough them by putting them in a list first:
matrix = [list1, list2, list3, list4]
then I would iterate through them and modify them like this:
new_matrix = [[],[],[],[]]
for i in range(len(matrix)):
new_matrix[i].extend(matrix[i][i:])
new_matrix[i].extend(matrix[i][0:i])
for i in range(len(new_matrix)):
print(new_matrix[i])
I'm sure there is a much better way to instantiate the new_matrix, but this works, the variable contains your 4 arrays shifted

Related

Is there any way i can append things into a list in different lines?

I was trying to append things into a list with each set of three elements getting appended line by line. So what I mean is:
ex = [John, 20/9/21, 234
Marc, 21/9/21, 53466]
So after appending each set of 3 elements line by line. I would like to find the index of the last element of each line. So in my case, I want 234 and 53466 from this list (there will be lines and lines of these sets of three elements, so I need a general way to find them).
If its always exactly sets of you can use array slicing
ex = ['John', '20/9/21', 234, 'Marc', '21/9/21', 53466, 'Peter', '22/9/21', 93879]
print(ex[2::3])
>> [234, 53466, 93879]
[2::3] means start at index 2 to the end in steps of 3.
Realistically you might consider moving to 2D arrays or more advanced structures i.e. with pandas
The trick is to append a tuple of data. That way you can treat your structure as a matrix / table.
l = []
l.append(('John' , '21/10/21' , 238))
l.append(('Marc' , '23/06/21' , 1586))
print(l)
for row in l:
print(row)
for cell in row:
print(cell)
print(l[1][1])
print(l[0][2])
Beware to NOT use l += ('...'), because if you then print out a certain index you will get that single character / number. So use l.append(...)!
I hope this is what you're looking for

how do you split list into x lists without using the elements on the inside?

Working on an assignment, which in one of the parts requires me to split the list into "x" chunks of lists but I don't necessarily want to use the elements inside the list to do so as I have seen many examples that do this. For example, given the list [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], I want to split this list into 3 even parts ([[1,2,3,4,5],[6,7,8,9,10],[11,12,14,15]]).
Most of the examples that I have seen on here tend to divide the whole list by "x" rather than making "x" groups of it which end up giving me a list like [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]].
EDIT:
I've figured out how to get the desired output in the first part of this question that I was looking for but upon looking at my assignment further, I realized the lists that need to be made have to go up in increments of lst rather than having to put a value in which would generate a list in that range. For example if I want to print out a grouped list like [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]] I don't want to have have to set lst to lst = list(range(1,lst+1)) and then when I'm assigning values to my function, I want to be able to put 5 in place of 15 to get the same result.
def test(num, lst, start = 1):
lst = list(range(start,lst+1))
avg = len(lst) / float(num)
out = []
last = 0.0
while last < len(lst):
out.append(lst[int(last):int(last + avg)])
last += avg
return out
print (test(3,15))
Most of the examples that I have seen on here tend to divide the whole list by "x" rather than making "x" groups of it which end up giving me a list like [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]].
In your example, a list of 15 elements divided into chunks of 3 makes 5 groups. It's too bad you didn't want five groups instead of three, you would have been done already!
If only there was a way to divide 15 elements with different sized chunks such that you would have 3 groups =)
Hint:
3 x 5 = 15
5 x 3 = 15
tl;dr: If you believe that dividing a list into chunks of size "x" is different than making "y" groups, then you should take a minute to reconsider.

List item changed across multiple items in a list [duplicate]

This question already has answers here:
How to deep copy a list?
(10 answers)
Closed 5 years ago.
I understand where my problem is stemming from, I simply do not know how to fix it.
for x in listoflists:
if x[1] == [1,0]:
q=[0, 0]
for z in range(5):
q[z] = x[:]
q[z][1] = [0,1]
q[z][0][-1] = q[z][0][-1] * 1.25
print(id(q[z][0][-1]))
list.append(q)
What I am trying to do is:
go into some data that I have gathered and make copies where I have switched a data label from [1,0] to [0,1]
then go into the zero index and multiply the price column by some factor to scale it up.
What I currently have is changing all prior values to be what I want the last value to be.
I understand this is something to do with python handling lists as references.
I had to change my first line to be a slice of x to alleviate this, but I do not know how to get around the parts where I take specifically indexed list items because it is showing the id as two different memory spaces.
All of the solutions I have seen show list comprehensions but I do not know how that applies to my case, because it seems like my z indexing is working correctly and they all have separate memory ids.
You need to do deep copy. Slicing does shallow copy.
from copy import deepcopy
lst1 = ['a','b',['ab','ba']]
lst2 = deepcopy(lst1)
id(lst1[2])
# 4451912
id(lst2[2])
# 51003144

How to order a list based on what a function returns when called with its items

Basically, I need to order a 2D array. Genes is an array of 8 lists, all containing 8 items, all of which are floats. This is for an evolution simulator of sorts, hence 'genes'. My current solution is this:
scores = []
[scores.append(score(x)) for x in genes]
unsorted = genes
genes = [unsorted[0]]
for y in range(7):
for x in range(len(genes)):
if score(unsorted[y+1]) >= score(genes[x]):
genes.insert(x, unsorted[y+1])
break
I have a list of all the scores, I save a copy of 'genes' called 'unsorted', and set genes as the first item it once contained. The nested loop underneath should run through unsorted, taking each item through the 'x' loop, and inserting it into 'genes' once it finds the first item of score equal or smaller than its own. I thought this would work, but for some reason, it returns lists of random sizes, like 3, 2 and 5 or even 16. If you have a more efficient or pythonic way to do this, or just one that works, please help!
That is what sorted is for.
genes = sorted(genes, key=score)

randomly selecting items from an array python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I randomly select an item from a list using Python?
I have two arrays pool_list_X , pool_list_Y. Both have a numpy array as element in the list.
So basically
pool_list_x[0] = [1 2 3 4] # a multidimensional numpy array.
and every element of pool_list_x has corresponding element in pool_list_y
which is to say, that pool_list_x[i] corresponds to pool_list_y[i]
Now. if I have to randomly select 10 elements from list_x (and hence the corresponding elements to list_y). how do i do this.
I can think of a very naive way.. randomly generate numbers. and stuff.. but that is not very efficient.. what is the pythonic way to do this.
Thanks
Not sure if I understand you one hundred percent, but I think using zip and random.sample might work:
import random
random.sample(zip(list_a,list_b), 10)
Some short explanations:
zip will create a list of pairs, i.e. it ensures that you pick corresponding elements - if you pick one, you automatically get the other (Zip([1,2,3],[4,5,6]) = [(1,4),(2,5),(3,6)])
random.sample(l,n) randomly selects n elements from a list l
There is a function allowing you to get the random element of the given sequence:
import random
my_choice = random.choice(my_sequence)
For details see the documentation.

Categories

Resources