Related
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)
I have the following list:
y = [[0], [0], [0], [0], [1], [1], [1], [1]]
I would like to transpose it and have it in the following form:
[[0]
[0]
[0]
[0]
[1]
[1]
[1]
[1]]
When I did numpy.transpose(y), I got the following:
[[0 0 0 0 1 1 1 1]]
Any ideas?
[[0], [0], [0], [0], [1], [1], [1], [1]]
is exactly the same as this form:
[[0]
[0]
[0]
[0]
[1]
[1]
[1]
[1]]
You had a matrix with 8 rows and 1 column. Transposition executed on the matrix converted it to a matrix with just 1 row and 8 columns, so the output was correct.
If y is a list of lists, it displays as a single line
In [1]: y = [[0], [0], [0], [0], [1], [1], [1], [1]]
In [2]: y
Out[2]: [[0], [0], [0], [0], [1], [1], [1], [1]]
In [3]: print(y)
[[0], [0], [0], [0], [1], [1], [1], [1]]
You could of course do a line by line print
In [4]: for i in y: print(i)
[0]
[0]
[0]
[0]
[1]
[1]
[1]
[1]
If I make an array from it, I get a 2d (n,1) array
In [5]: Y = np.array(y)
In [6]: Y
Out[6]:
array([[0],
[0],
[0],
[0],
[1],
[1],
[1],
[1]])
In [7]: print(Y)
[[0]
[0]
[0]
[0]
[1]
[1]
[1]
[1]]
The array display does show rows and columns. Note that array print does not include commas (but its repr does).
If I transpose it, I get a (1,n) array, which displays as 1 line
In [8]: Y.T
Out[8]: array([[0, 0, 0, 0, 1, 1, 1, 1]])
There 3 different things that you may be confusing - the list, its print or string representation, and an array constructed from the list (and its print).
There is a list version of 'transpose':
In [9]: list(zip(*y))
Out[9]: [(0, 0, 0, 0, 1, 1, 1, 1)]
A longer list of lists may display as you want (if it doesn't neatly fit one line):
In [20]: z=[[i] for i in range(15)]
In [21]: z
Out[21]:
[[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9],
[10],
[11],
[12],
[13],
[14]]
Except - that's an ipython pretty print action. In a plain python
shell
>>> [[i] for i in range(15)]
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]]
Which just emphasizes my point - there's a difference between a list and its print representation.
There is a pprint.pprint (pretty print) that behaves more like ipython, switching to row prints when the list gets too long.
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 have a feeling that this is very easy but I can't quite figure out how to do it. Say I have a Numpy array
[1,2,3,4]
How do I convert this to
[[1],[2],[3],[4]]
In an easy way?
Thanks
You can use np.newaxis:
>>> a = np.array([1,2,3,4]
array([1, 2, 3, 4])
>>> a[:,np.newaxis]
array([[1],
[2],
[3],
[4]])
You can use numpy.reshape:
>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> np.reshape(a, (-1, 1))
array([[1],
[2],
[3],
[4]])
If you want normal python list then use list comprehension:
>>> a = np.array([1,2,3,4])
>>> [[x] for x in a]
[[1], [2], [3], [4]]
The most obvious way that comes to mind is:
>>> new = []
>>> for m in a:
new.append([m])
but this creates normal Python's list of lists, I'm not sure if this is what you want...
>>> A = [1,2,3,4]
>>> B = [[x] for x in A]
>>> print B
[[1], [2], [3], [4]]
This follows on from this question:
Algorithm to generate spanning set
Given this input: [1,2,3,4]
I'd like to generate this set of sets in python:
[1] [2] [3] [4]
[1] [2] [3,4]
[1] [2, 3, 4]
[1] [2,3] [4]
[1,2] [3] [4]
[1,2] [3,4]
[1,2,3] [4]
[1,2,3,4]
So unlike the previous question, the order of the list is retained.
Ideally the code would work for n items in the list
Thanks very much
EDIT 2: Could anyone advise me on how to do this if the original input is a string rather than a list (where each word in the string becomes an item in a list). Thanks!
EDIT: added [1] [2, 3, 4] Sorry for the mistake
You might also enjoy a recursive solution:
def span(lst):
yield [lst]
for i in range(1, len(lst)):
for x in span(lst[i:]):
yield [lst[:i]] + x
Explanation
We exploit recursion here to break the problem down. The approach is the following:
For every list, the whole list is a valid spanning: [1,2,3,4] => [[1,2,3,4]].
For every list that is longer than size 1, we can use the first item as a group and then apply the same algorithm on the remaining list to get all the combined results:
[1,2,3] =>
[[1]] + [[2], [3]] # => [[1], [2], [3]]
[[1]] + [[2,3]] # => [[1], [2,3]]
For every list that is longer than size 2, we can just as well use the first two items as a group and then apply the same algorithm on the remaining list and combine the results:
[1,2,3,4,5] =>
[[1,2]] + [[3], [4], [5]] # => [[1,2], [3], [4], [5]]
[[1,2]] + [[3,4], [5]] # => [[1,2], [3,4], [5]]
[[1,2]] + [[3], [4,5]] # => [[1,2], [3], [4,5]]
[[1,2]] + [[3,4,5]] # => [[1,2], [3,4,5]]
We can see that the possible combinations on the right side are indeed all possible groupings of the remainder of the list, [3,4,5].
For every list that is longer than ... etc. Thus, the final algorithm is the following:
yield the whole list (it is always a valid spanning, see above)
For every possible splitting of the list, yield the left-hand part of the list combined with all possible spannings of the right-hand part of the list.
yield is a special keyword in Python that make the function a generator, which means that it returns a iterable object that can be used to enumerate all results found. You can transform the result into a list using the list constructor function: list(span([1,2,3,4])).
Adjusting one of the solution from Python: show all possible groupings of a list:
from itertools import combinations
def cut(lst, indexes):
last = 0
for i in indexes:
yield lst[last:i]
last = i
yield lst[last:]
def generate(lst, n):
for indexes in combinations(list(range(1,len(lst))), n - 1):
yield list(cut(lst, indexes))
data = [1,2,3,4]
for i in range(1, len(data)+1): # the only difference is here
for g in generate(data, i):
print(g)
"""
[[1, 2, 3, 4]]
[[1], [2, 3, 4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]
[[1], [2], [3, 4]]
[[1], [2, 3], [4]]
[[1, 2], [3], [4]]
[[1], [2], [3], [4]]
"""
import itertools
a = [1, 2, 3, 4]
n = len(a)
for num_splits in range(n):
for splits in itertools.combinations(range(1, n), num_splits):
splices = zip([0] + list(splits), list(splits) + [n])
print([a[i:j] for i, j in splices])
prints
[[1, 2, 3, 4]]
[[1], [2, 3, 4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]
[[1], [2], [3, 4]]
[[1], [2, 3], [4]]
[[1, 2], [3], [4]]
[[1], [2], [3], [4]]