How can I take a nested List and group it into a tuple of three without importing any module. Please show the expanded for loops so I can understand it better.
For example, I want this nested List. Note this will always multiples of
3 sub lists so there is not a index error.
Thankyou.
[[1], [2], [3], [4], [5], [6], [7], [8], [9]] # Given
[(1, 2, 3), (4, 5, 6), (7, 8, 9)] # Result Wanted
No need for indexes. You can use next() on an iterator even inside a for loop:
xss = [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
it = iter(xss)
answer = []
for x, in it:
answer.append((x, next(it)[0], next(it)[0]))
You can slice with a step size of 3 and zip to make the triples, do a nested unpacking in the for loop, and rebuild the triples without the wrapping lists.
xss = [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
it = zip(xss[::3], xss[1::3], xss[2::3])
answer = []
for [x], [y], [z] in it:
answer.append((x, y, z))
given = [[1], [2], [3], [4], [5], [6], [7], [8], [9]] # because this is a list within a list
output = []
for i in range(0, len(given),3): # step size 3 indicated
temp = (given[i][0], given[i+1][0], given[i+2][0]) # therefore you need the "[0]" behind each given[i]
output.append(temp)
print (output)
Related
I have two lists I want to merge into one like so:
list_0=[[5], [4], [4], [1], [0], [7], [8], [3], [0]]
list_1=[[0], [9], [6], [4], [5], [9], [5], [9], [3]]
mine_position=[[5], [0], [4], [9], [4], [6], [1], [4], [0], [5], [7], [9], [8], [5], [3], [9], [0], [3]]
The code I have for merging them is:
for i in row:
mine_position.append(i)
mine_position.insert(1, list_1[0])
mine_position.insert(3, list_1[1])
mine_position.insert(5, list_1[2])
mine_position.insert(7, list_1[3])
mine_position.insert(9, list_1[4])
mine_position.insert(11, list_1[5])
mine_position.insert(13, list_1[6])
mine_position.insert(15, list_1[7])
mine_position.insert(17, list_1[8])
I want to shorten it so that the second part can be cleaner, but I can't seem to find a method that works.
You can just zip them together. No loops needed.
list_0=[[5], [4], [4], [1], [0], [7], [8], [3], [0]]
list_1=[[0], [9], [6], [4], [5], [9], [5], [9], [3]]
mine_position = list(zip(list_0, list_1))
We can see that your merged list's elements at even indices consists of elements from list_0 and the odd indices consists of elements from list_1. The below code snippet can be used to generate the merged list.
Code Snippet:
# Original Lists
list_0=[[5], [4], [4], [1], [0], [7], [8], [3], [0]]
list_1=[[0], [9], [6], [4], [5], [9], [5], [9], [3]]
# Merged List
result = []
total_elements = len(list_0) + len(list_1)
# Indices of respective lists
list0_idx = list1_idx = 0
for i in range(total_elements):
if i % 2 == 0:
result.append(list_0[list0_idx])
list0_idx += 1
else:
result.append(list_1[list1_idx])
list1_idx += 1
print(result)
How about this?
list_0=[[5], [4], [4], [1], [0], [7], [8], [3], [0]]
list_1=[[0], [9], [6], [4], [5], [9], [5], [9], [3]]
merged_list = []
for i in range(0, len(list_0)):
merged_list.append(list_0[i])
merged_list.append(list_1[i])
print(merged_list)
It shows this.
[[5], [0], [4], [9], [4], [6], [1], [4], [0], [5], [7], [9], [8], [5], [3], [9], [0], [3]]
You can first create a new variable and assign it as list_0. We do this so that list_0 is not altered. Then use a loop and insert the element of list_1 every 2 elements.
list_0=[[5], [4], [4], [1], [0], [7], [8], [3], [0]]
list_1=[[0], [9], [6], [4], [5], [9], [5], [9], [3]]
merged_list = list_0
idx = 1
for j in list_1:
merged_list.insert(idx,j)
idx += 2
print(merged_list)
#Result: [[5], [0], [4], [9], [4], [6], [1], [4], [0], [5], [7], [9], [8], [5], [3], [9], [0], [3]]
NOTE the reason we increment it by 2, is because at the start of the iteration, a new element will be added into the merged_list.
Using list comprehension:
[item for t in [(list_0[i], list_1[i]) for i in range(len(list_0))] for item in t]
I have a nested list say:
lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
And I would like the output to be:
new_list = [[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
this is what i am thinking, but I it is outputting a flat, list of list.
new_lst = []
for i in lst:
i = list(i)
for el in i:
new_list.append([el])
print(new_lst)
I would like to maintain the length of each predefined list in lst
Try List comprehension
[[ [e] for e in l] for l in lst]
You could use list comprehension and append every element to another list.
lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
new = [[[numbers] for numbers in elements] for elements in lst]
The above example adjusts for your desired output.
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
You can use numpy's reshape np.reshape
>>> import numpy as np
>>> lst = np.array([[1,2,3,4], [2,3,4,5], [3,4,5,6]])
>>> lst
array([[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]])
>>> lst.shape
(3, 4)
>>> lst.reshape(3,4,1)
array([[[1],
[2],
[3],
[4]],
[[2],
[3],
[4],
[5]],
[[3],
[4],
[5],
[6]]])
>>> lst.reshape(3,4,1).tolist()
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
Another version, using recursion (you can have more level of depths in your input):
lst = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
def split(i):
if isinstance(i, list):
return [split(v) for v in i]
else:
return [i]
print(split(lst))
Prints:
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
You could use helper function to have more flexibility later of how you divide the smaller lists. based on an answer from here.
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts) ]
lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
ret =[]
for mini_list in lst:
ret.append(split_list(mini_list, len(mini_list)))
I think you had the right idea using multiple for loops. This should work:
list = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
for i in range(0, 3):
for j in range(0, 4):
(list[i])[j] = [(list[i])[j]]
I have 2 lists
A= matrix([[ 9],
[5],
[7],
[ 8]]), matrix([[2],
[3],
[7],
[8])]
B = matrix([[ 3],
[2],
[1],
[ 4]]), matrix([[2],
[3],
[2],
[5])]
I want subtract the first matrix in the second list B from the first matrix in the first list A. To get the matrix
matrix([[3],
[3],
[6],
[4])
then the second from the second, and add these new matrices to a new list C.
I tried the code
C=list()
for j in A :
for k in B:
C.append(j-k)
But it's not giving the correct answers . What are your suggestions?
firstly sorry I know this place isn't really somewhere to go to ask for someone to do something for you, but I'm just quite frustrated currently.
If it would be possible for someone to help me turn this:
grid = [[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]
Into something that would output:
[1] [2] [3]
[4] [5] [6]
[7] [8] [9]
Again, really sorry about asking this, but I just need all the help I can get.
You can iterate through your list of lists and print each row:
for gridRow in grid:
print(gridRow)
to get the following output
[[1], [2], [3]]
[[4], [5], [6]]
[[7], [8], [9]]
Additional formatting upon each iteration would be necessary to get your exact desired format:
for gridRow in grid:
#map(str, gridRow) is necessary because your list contains numbers
#if they were strings, just " ".join(gridRow) would be fine
rowOut = " ".join(map(str, gridRow))
print(rowOut)
prints exactly what you asked.
grid = [[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]
for row in grid:
for element in row:
print(element, end="")
print()
Using stdio you can print out the data in the format you want.
import stdio
grid = [[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]
for i in range(len(grid)):
for j in range(len(grid)):
stdio.write(str(grid[i][j]))
stdio.writeln("\n")
[1] [2] [3]
[4] [5] [6]
[7] [8] [9]
I am not sure if what I am asking is possible, but it would be convenient for a particular application if it were. I am building a trial list for an experiment, where a target can either match a prime exactly, or it can be a mismatch in a particular way that maintains a certain relationship to the target. To be even more explicit, all of my stimuli fall into a 3 level taxonomy, of the form:
H = {
'A1':{
'B1':{
'C1':[],'C2':[],'C3':[] },
'B2':{
'C1':[],'C2':[],'C3':[] },
'B3':{
'C1':[],'C2':[],'C3':[] }
},
'A2':{
'B1':{
'C1':[],'C2':[],'C3':[] },
'B2':{
'C1':[],'C2':[],'C3':[] },
'B3':{
'C1':[],'C2':[],'C3':[] }
}
}
Where each list on the bottom the the "tree" is a particular set of stimuli. If the prime and target match, that is simple. If they do not, I want to draw randomly, without replacement, from a different C group under the same B group.
My intended solution was to leverage how (I thought) python handles references and make a temporary list that I could pop() a stimuli from. So, if the trial is incongruent, and the prime is from H[A1][B1][C1], I want to pop() from a list:
tempList = H[A1][B1][C2] + H[A1][B1][C3]
However, presumably because I am appending the two lists, the reference to the lists in the dictionaries is broken, so if I remove an idem from the temp list, it is not reflected in the dictionaries. Is there a way to maintain the reference? Thank you!
EDIT:
This toy example does not work as expected:
>>> d = {'A':[1,2,3],'B':[4,5,6]}
>>> l = d['A'] + d['B']
>>> l
[1, 2, 3, 4, 5, 6]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5, 6]
>>> d
{'A': [1, 2, 3], 'B': [4, 5, 6]}
Create a new class that takes H and the paths to the sublists in the initializer, and override __*item__() such that the underlying lists will be affected instead.
EDIT:
A partial example:
class listxer(object):
def __init__(self, structure, paths):
self.structure = structure
self.paths = paths
def _descend(self, path):
return reduce(lambda x,y: x[y], path, self.structure)
def __len__(self):
return sum(len(self._descend(path)) for path in self.paths)
def __getitem__(self, item):
if item < 0:
raise ValueError('negative indices not supported!')
for path in self.paths:
cur = self._descend(path)
if item > len(cur):
item -= len(cur)
continue
else:
return cur[item]
else:
raise IndexError('list index out of range')
H = [[[1, 2], [3, 4, 5]]]
mystruct = listxer(H, ((0, 0), (0, 1)))
print len(mystruct)
print mystruct[3]
Though it would be difficult for me to give a specialized solution but I will try to give you the answer to your underline question
Given two list, A & B, how to generate a List C such that
if C = A + B
changing C would eventually change either A or B.
Take the following example
I create two lists A & B which are themselves lists of numbers.
>>> A=[[i] for i in range(0,10)]
>>> B=[[i] for i in range(10,20)]
I then add them up.
>>> C=A+B
Now if I change any element of C it would either change A or B
>>> C[1][0]=-1
>>> C
[[0], [-1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]]
>>> A
[[0], [-1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>> C[11][0]=-1
>>> C
[[0], [-1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [-1], [12], [13], [14], [15], [16], [17], [18], [19]]
>>> B
[[10], [-1], [12], [13], [14], [15], [16], [17], [18], [19]]
>>>