如何从python3中的单行输入读取整数数组 [英] How to read an array of integers from single line of input in python3

查看:63
本文介绍了如何从python3中的单行输入读取整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从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

我尝试了什么

  1. arr = input.split(' ') 但这不会将它们转换为整数.它创建字符串数组

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

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.

推荐答案

使用map:

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

补充一点,在 Python 2.x 中你不需要调用 list(),因为 map() 已经返回了一个 list,但在 Python 3.x 许多迭代可迭代对象的进程本身返回迭代器".

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".

此输入必须添加 () 即括号对才能遇到错误.这适用于 3.x 和 2.x Python

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

这篇关于如何从python3中的单行输入读取整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆