如何在python中将N个空格分隔的数字转换为数组? [英] how to convert N space separated numbers into in array in python?

查看:44
本文介绍了如何在python中将N个空格分隔的数字转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中输入以空格分隔的n个整数?
假设我想在一个以空格分隔的数组中输入 n 个元素,例如

How do I input n integers separated by space in python?
Suppose I want to input n elements in an array separated by space such as

3
1 2 3

那么有什么办法吗?
编辑 - 在第一行中,我们给出了 n,在下一行中,接下来是 n 个输入.是否可以将它们存储在数组中?

So is there any way to do it?
EDIT - In first line we are given n and in next line n inputs follow. Is it possible to store them in an array?

推荐答案

两种方式:

1) 使用 raw_input().这会提示用户输入输入

1) using raw_input(). This prompts user to enter inputs

int_list = [int(x) for x in raw_input("Enter integers:").split()]

2) 使用sys.argv,你可以从命令行指定输入

2) using sys.argv, you can specify input from the command line

import sys
int_list = [int(x) for x in sys.argv[1:]]

这篇关于如何在python中将N个空格分隔的数字转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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