I have printed the elements of a list of lists like this:
['1', 'A']
['1', 'B']
['2', 'A']
['2', 'B']
['3', 'A']
['3', 'B']
I am wondering how can I print that elements like this (a 3*2 matrix in this case):
['1', 'A'] ['1', 'B']
['2', 'A'] ['2', 'B']
['3', 'A'] ['3', 'B']
The number of rows is the number of different numbers and the number of columns is the number of different letters.
For instance, if I have:
['1', 'A']
['1', 'B']
The output would be displayed in 1 row and 2 columns:
['1', 'A'] ['1', 'B']
At this moment I have tried converting the list of lists into a numpy array and try to print the desired output but it does not work:
lst = [['1', 'A'],['1', 'B'],['2', 'A'],['2', 'B'],['3', 'A'],['3', 'B']]
arr = numpy.array(lst)
arr = arr.reshape(3,2)
print(*arr)
Examples:
Input:
[['1', 'A'],['1', 'B'] ,['1', 'C'], ['1', 'D']]
Output:
['1', 'A']['1', 'B'] ['1', 'C'] ['1', 'D']
Input:
[['1', 'A'],['1', 'B'] ,['1', 'C'], ['1', 'D'],['2', 'A'],['2', 'B'] ,['2', 'C'], ['1', 'D']]
Output:
['1', 'A']['1', 'B'] ['1', 'C'] ['1', 'D']
['2', 'A']['2', 'B'] ['2', 'C'] ['2', 'D']
Input:
[['1', 'A'],['1', 'B'],['2', 'A'],['2', 'B'],['3', 'A'],['3', 'B']]
Output:
['1', 'A']['1', 'B']
['2', 'A']['2', 'B']
['3', 'A']['3', 'B']
CodePudding user response:
Here is a python only version
tmp = list(map(str, lst))
s = '\n'.join([' ' .join((l1, l2)) for l1, l2 in zip(tmp[::2], tmp[1::2])])
print(s)
output:
['1', 'A'] ['1', 'B']
['2', 'A'] ['2', 'B']
['3', 'A'] ['3', 'B']
CodePudding user response:
Try this:
import numpy as np
import pandas as pd
lst = [['1', 'A'],['1', 'B'],['2', 'A'],['2', 'B'],['3', 'A'],['3', 'B']]
def show(lst):
df = pd.DataFrame(lst, columns=['number', 'letter'])
a = []
for x in df['letter'].unique():
a.append(np.array(df[df['letter']==x]))
a = np.array(a)
for i in range(a.shape[1]):
p = ' '.join([str(list(a[j,i])) for j in range(a.shape[0])])
print(p)
show(lst)
Output:
['1', 'A']['1', 'B']
['2', 'A']['2', 'B']
['3', 'A']['3', 'B']
If you have more letters and more rows, then this function will still work.
lst = [['1', 'A'],['1', 'B'],['1', 'C'],['1', 'D'],['1', 'E'],['2', 'A'],['2', 'B'],['2', 'C'],['2', 'D'],['2','E'],['3', 'A'],['3', 'B'],['3', 'C'],['3', 'D'], ['3', 'E'],['4', 'A'],['4', 'B'],['4', 'C'],['4', 'D'], ['4', 'E']]
show(lst)
Output:
['1', 'A'] ['1', 'B'] ['1', 'C'] ['1', 'D'] ['1', 'E']
['2', 'A'] ['2', 'B'] ['2', 'C'] ['2', 'D'] ['2', 'E']
['3', 'A'] ['3', 'B'] ['3', 'C'] ['3', 'D'] ['3', 'E']
['4', 'A'] ['4', 'B'] ['4', 'C'] ['4', 'D'] ['4', 'E']
CodePudding user response:
For your specific list, you probably want to reshape it to (3, 2, 2)
- i.e. n_rows * n_cols * n_elements_in_sublist
lst = [['1', 'A'],['1', 'B'],['2', 'A'],['2', 'B'],['3', 'A'],['3', 'B']]
arr = numpy.array(lst).reshape(3, 2, 2)
You can extract the n_rows
and n_cols
from list as
n_rows = len(set(x for x,y in lst))
n_cols = len(set(y for x,y in lst))