0

I need to place user input in a multi dimension list in python. I am new at Python. Some user inputs would be

11001111
10001100
11000000

I need to place them in list

a[[1,1,0,0,1,1,1,1],[1,0,0,0,1,1,0,0],[1,1,0,0,0,0,0,0]]

What I do. And its completely useless

for i in range(3):
    for b in range(7):
        a[i][b] = int(input())

4 Answers 4

3

You can either read a line at a time and process individual characters:

for i in range(3):
    line = input()
    for b in range(7):
        a[i][b] = int(line[b])

Or you can read a character at a time:

sys.stdin.read(1)
Sign up to request clarification or add additional context in comments.

Comments

1

If you accept that the users types 21 digits+enter each time, what you're doing works, although it isn't the best way, looks a lot like C code.

However, it's not useless, it works provided you initialize your bidimensional array properly for instance like this:

a = [[0]*7 for _ in range(3)]

this creates 3 lists of 7 elements. You can read/write them with this exact loop you posted.

If you want to read 3 lines of single digit numbers, you could do it in only like using double list comprehension:

a = [[int(x) for x in input()] for _ in range(3) ]

Comments

0

This could work too :

a = []
for x in range(3):
    a.append([int(let) for let in input('enter number:\n')])

4 Comments

This one Exactly Works for me: Thanks
@sagarDevkoka thanks, you should consider using solution from @Jean-francois-fabre too, with a pretty one-liner a = [[int(x) for x in input('enter number:\n')] for _ in range(3) ]
How can i accept string in list? I should give two lines and I Should keep each line in one index? how can I do that?
@sagarDevkoka this depends on how you want to handle the result object later, but if you need to store entire strings, this code cannot work and another input/process is required
0

Try doing this:

a = []
for i in range(3):
    k = raw_input()
    a.append([int(j) for j in k])

print a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.