Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

python - How to read an array of integers from single line of input in python3

I want to read an array of integers from single line of input in python3. For example: Read this array to a variable/list

1 3 5 7 9

What I have tried

  1. arr = input.split(' ') But this does not convert them to integers. It creates array of strings

  2. arr = input.split(' ')

    for i,val in enumerate(arr): arr[i] = int(val)

2nd one is working for me. But I am looking for an elegant(Single line) solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use map:

arr = list(map(int, input().split()))

Just adding, in Python 2.x you don't need the to call list(), since map() already returns a list, but in Python 3.x "many processes that iterate over iterables return iterators themselves".

This input must be added with () i.e. parenthesis pairs to encounter the error. This works for both 3.x and 2.x Python


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...