I'm looking for a way to print a multidimensional lists in a specific way.
This is how my list full of int looks.
[[1,2,3],[4,5,6]]
or
[[1,2,3,4,5,6]]
I want to print each element with a space and a comma between the two 'big' elements in the list. So for my example the output would be:
1 2 3, 4 5 6
and
1 2 3 4 5 6
I use python 3.4.2
In [78]: L = [[1,2,3],[4,5,6]]
In [79]: ', '.join([' '.join([str(i) for i in subl]) for subl in L])
Out[79]: '1 2 3, 4 5 6'
In [80]: L = [[1,2,3,4,5,6]]
In [81]: ', '.join([' '.join([str(i) for i in subl]) for subl in L])
Out[81]: '1 2 3 4 5 6'
Strings can be easily joined using 'sep'.join(...) with sep being the separator. Before joining the numbers of one part of the array, you need to convert them to strings. This can be easily done using a map function. For each element in i it applies the str function. After joining the numbers of each part separated with a space, you can join the parts to the final result.
l = [[1,2,3],[4,5,6]]
print ', '.join([' '.join(map(str, i)) for i in l])
Output:
1 2 3, 4 5 6
Note: In Python 3 you need to call print with brackets: print(...).
>>> l = [[1, 2, 3], [4, 5, 6]]
>>> ', '.join(map(lambda x: ' '.join(map(str, x)), l))
'1 2 3, 4 5 6'
>>> l = [[1, 2, 3, 4, 5, 6]]
>>> ', '.join(map(lambda x: ' '.join(map(str, x)), l))
'1 2 3 4 5 6'
ls = [[1, 2, 3, 4], [5, 6, 7, 8]]
for n in range(0, len(ls)):
for m in range(0, len(ls[n])):
print(str(ls[n][m]) + ' ', end='')
if n < (len(ls)-1):
print(', ', end='')
else:
print('')
Related
Here is my problem,
import numpy
lst1 = [[1,2,3],[7,8,9]]
lst2 = [4,5,6]
lst1.extend(lst2)
print(len(lst1))
print(len(lst1[0]))
NewArr = numpy.asarray(lst1)
print(NewArr.shape)
print ("List:", lst1)
print ("Array: ", NewArr)
run this code, it print result :
5
3
(5,)
List: [[1, 2, 3], [7, 8, 9], 4, 5, 6]
Array: [list([1, 2, 3]) list([7, 8, 9]) 4 5 6]
but I want the result look like this:
5
3
(5,3)
List: [[1,2,3,4,5,6],[7,8,9]]
Array: [list([1,2,3,4,5,6]) list([7,8,9])]
could someone help me please?
Your are extending the whole list, not the first element of the list.
You should write:
lst1[0].extend(lst2)
Which gives you your result:
list([list([1,2,3,4,5,6]) list([7,8,9])])
However, your first 2 print-statements should also be:
print(len(lst1[0])) # 5
print(len(lst1[1])) # 3
Note: code created in python 2.7
I am taking a robotics class in school and we are learning python.
The task was to take
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
and print it out as such
1
2
3
4
5
6
7
8
9
When I tried my code out I got the error message
I tried looking at what this means online but I am just starting to learn python and I didn't understand any of the answers that I found.
What am I doing wrong? How do I fix my code?
First Post sorry about the mess
Reason why you get an error:
You get the error in the line
results.append(lists[numbers[each_list]])
because numbers is an integer and numbers[each_list] isn't a valid function. So instead use the square brackets correctly:
results.append(lists[numbers][each_list])
Other Methods:
You don't really need to use range function:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
for i in n:
for j in i:
print(j)
or a one liner:
print('\n'.join(str(j) for i in n for j in i))
Or if you are flattening a nested list:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flat(lis):
res = []
for i in lis:
for j in i:
res.append(j)
return res
flat_n = flat(n)
or a one-liner:
>>> n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>>> flat = lambda x: [j for i in x for j in i]
>>> flat(n)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
or just simply:
flat_n = [j for i in n for j in i]
n=[[1,2,3],[4,5,6,7,8,9]]
def flatten(lists):
results=[]
for lists in n:
for numbers in lists:
results.append(numbers)
return results
new_list =(flatten(n))
for num in new_list:
print (num)
When Executed
1
2
3
4
5
6
7
8
9
>>>
I have a nested sequence that I want to flatten into a single list of values.
Please try this general solution:
Write a recursive generator function involving a yield from
statement. For example:
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x, ignore_types)
else:
yield x
items = [1, 2, [3, 4, [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
print(x)
I'd go with recursion but split in a balanced way.
def flatten(lst):
n = len(lst)
if n == 0:
return lst
elif n == 1:
item = lst[0]
try:
return flatten(list(item))
except TypeError:
return [item]
else:
k = n // 2
return flatten(lst[:k]) + flatten(lst[k:])
Demo
items = [1, 2, [3, 4, [5, 6], 7], 8]
flatten(items)
[1, 2, 3, 4, 5, 6, 7, 8]
There is an array [1, 2, ..., m], and there is an integer n.
If m=2 and n=3, I want to obtain
[1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[1, 2, 2]
[2, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 2, 2]
It's like I do
for i=1:m
for j=1:m
for k=1:m
\\ get [i, j, k]
end
end
end
But, both m and n are variables. How can I do this? I'm using Julia, but any general advice would be fine.
It's not clear to me what you mean by "I want to obtain" and \\ get [i, j, k], but you may find this useful/interesting.
julia> using Iterators
julia> collect(product(repeated(1:2,3)...))
8-element Array{(Int32,Int32,Int32),1}:
(1,1,1)
(2,1,1)
(1,2,1)
(2,2,1)
(1,1,2)
(2,1,2)
(1,2,2)
(2,2,2)
julia> A=reshape(1:8,(2,2,2))
2x2x2 Array{Int32,3}:
[:, :, 1] =
1 3
2 4
[:, :, 2] =
5 7
6 8
julia> for i in product(repeated(1:2,3)...)
#show A[i...]
end
A[i...] => 1
A[i...] => 2
A[i...] => 3
A[i...] => 4
A[i...] => 5
A[i...] => 6
A[i...] => 7
A[i...] => 8
julia> cartesianmap((k...)->println(A[k...]^2+1),tuple(repeated(2,3)...))
2
5
10
17
26
37
50
65
or even without the Iterators package ...
julia> cartesianmap((k...)->println(A[k...]),tuple(repmat([2],3)...))
1
2
3
4
5
6
7
8
This is not Julia specific but what I do generally in such a case is (pseudo code):
array = [1, 1, 1, .., 1] # ones n times
while True
# increased last element by one
array(end) += 1
# looking at overflows from end to beginning
for i = n:-1:2
if array(i) > m
array(i) = 1
array(i-1) += 1
end
end
# if overflow in the first entry, stop
if array(1) > m
break
end
# do something with array, it contains the indices now
..
end
hopefully it is simple question......
I have two arrays:
>>> X1=[1,2,4,5,7,3,]
>>> X2=[34,31,34,32,45,41]
I want to put these arrays in to a matrix called X:
X=[[1 23]
[2 31]
[4 34]
[5 32]
[7 45]
[3 41]]
Expected output is like the following:
>>>Print X[:0]
[1
2
4
5
7
3]
>>>print X[:1]
[34
31
34
32
45
41]
my problem it putting the two array in to a matrix, what I used before is
X=[[X1[i],X2[i]] for i in range(len(X1))]
But when i try to print
>>>print X[:0]
I got error like:
TypeError: list indices must be integers, not tuple
What really I want is when i print
Print X[0] it must outputs [1,23]
print x[:0] it must outputs the first column of the matrix
Need your help....thanks!!
You cannot index lists in that manner. Your resulting matrix is just a list. You could create a dataframe to get the functionality you seem to want:
import pandas as pd
X1=[1,2,4,5,7,3,]
X2=[34,31,34,32,45,41]
matrix = [[x, y] for x, y in zip(X1, X2)]
df = pd.DataFrame(matrix)
print df[0]
print df[1]
prints:
0 1
1 2
2 4
3 5
4 7
5 3
Name: 0, dtype: int64
0 34
1 31
2 34
3 32
4 45
5 41
Name: 1, dtype: int64
Alternatively create a numpy.matrix and slice it as you want it:
n_matrix = np.matrix(zip(X1,X2))
print n_matrix[0:, 0]
print n_matrix[0:, 1]
prints
[[1]
[2]
[4]
[5]
[7]
[3]]
[[34]
[31]
[34]
[32]
[45]
[41]]
For the first part, you can use zip if tuples are ok for your need:
>>> X1=[1,2,4,5,7,3,]
>>> X2=[34,31,34,32,45,41]
>>> list(zip(X1, X2))
[(1, 34), (2, 31), (4, 34), (5, 32), (7, 45), (3, 41)]
or:
>>> [[a, b] for a, b in zip(X1, X2)]
[[1, 34], [2, 31], [4, 34], [5, 32], [7, 45], [3, 41]]
I can't reproduce your last error:
>>> X=[[X1[i],X2[i]] for i in range(len(X1))]
>>> print X[:0]
[]
You probably tried to write:
>>> print X[:,0]
Which is valid using numpy's matrices:
>>> import numpy as np
>>> x= np.matrix([[a, b] for a, b in zip(X1, X2])
>>> print x
matrix([[ 1, 34],
[ 2, 31],
[ 4, 34],
[ 5, 32],
[ 7, 45],
[ 3, 41]])
>>> x[:,0]
matrix([[1],
[2],
[4],
[5],
[7],
[3]])
>>> x[:,1]
matrix([[34],
[31],
[34],
[32],
[45],
[41]])