简体   繁体   中英

get output element by element when input a list

enter image description here I want to enter numbers separated by spaces as input. Store the numbers in a list and get the elements by elements in that list as output.

This was my code.

lst = input()
test_list =[]

for ele in lst.split():
    n_int = int(ele)
    test_list.append(n_int)

for i in range(len(test_list)):
    print(i)

When I enter a input like 4 7 9 , I expect an output like this. 4 7 9 But I get this output 0 1 2

You are using range() function which helps to go index by index in list if you wanted to go item by item you don't need to use range() you can simply access items by iterating see the below code..

for i in test_list:
    print(i)

You can also do with range() function simple accessing list by index and print..

for i in range(len(test_list)):
    print(test_list[i])

The above 2 solutions will give output

3
7
9 

If you wanted in same line like 3 7 9 you can use end in print

print(i,end=" ")    or    print(test_list[i],end=" ")

fist let's dissect your code flow:

test_list = ["4", "7", "9"]

Then: len(test_list) is 3

So

for i in range(3):
    print(i)

This will result in:

 0 1 2

You could get your printed desired output with:

for ele in lst.split():
    n_int = int(ele)
    test_list.append(n_int)
    print(ele)

Where print(ele) will print each number in your list.

Change your last lines:

try this:

print(test_list[i])

or this will work too:

for i in test_list:
    print(i)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM