I have a requirement where the input is of form
3 3
ABB
BAA
AAA
The first line of input indicates Number of row(3) and columns(3) respectively. And below lines indicate input string, which forms the 3*3 matrix.
I tried using Dictionary to create it and was able to achieve it, but is using Dictionary correct way or most efficient way. Is there any other way to create a 2D matrix of this form?
Using Lists:
print "Enter the value of row:"
r = input()
print "Enter the value of column:"
c = input()
m=[]
for i in xrange(r):
m.append([])
for j in xrange(c):
m[i].append(raw_input())
print m
The Input and output: Enter the value of row: 2 Enter the value of column: 2 ABB AAA BBB CCC
[['ABB', 'AAA'], ['BBB', 'CCC']]
The Input and output: Enter the value of row: 2 Enter the value of column: 2 ABB AAA BBB CCC
[['ABB', 'AAA'], ['BBB', 'CCC']]
I needed it of the form:
[[A,B,B],[A,A,A],[B,B,B],[C,C,C]]
Following code creates a 2d list for the above data.
f = open("data.txt")
rows_count, cols_count = f.readline().split()
line_count = 0
list2D = []
while line_count < int(rows_count):
line = f.readline().strip().strip("\n")
if len(line) == 0:
# blank line
continue
row = list(line)[0:int(cols_count)]
list2D.append(row)
line_count += 1
print list2D
Output:
[['A', 'B', 'B'], ['B', 'A', 'A'], ['A', 'A', 'A']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.