利用Python输入n个用空格分隔的整数 ← list(map(int,input().split()))

在算法设计中,经常需要输入 n 个用空格分隔的整数。现对其 Python 代码进行总结:
● 当 n=1 时:

python 复制代码
x=int(input())
print(x)

● 当 n=2 时:

python 复制代码
x,y=map(int,input().split()) #Enter numbers separated by space
sum=x+y
print(sum)
 
'''
in:
1 2
out:
3
'''

● 当 n=3 时:

python 复制代码
x,y,z=map(int,input().split()) #Enter numbers separated by space
sum=x+y+z
print(sum)
 
'''
in:
1 2 3
out:
6
'''

● 当 n>3 时:
代码一:不需预先输入 n 的值
(1)使用 list 与 map:list(map(int,input().split()))

python 复制代码
ls=list(map(int,input().split()))
sum=0
for x in ls:
    sum+=x
print(sum)

'''
in:5 3 1 2 7
out:18
'''

(2)使用 input().split()

python 复制代码
ls=input().split()
sum=0
for x in ls:
    sum+=int(x)
print(sum)

'''
in:5 3 1 2 7
out:18
'''

**注意:**命令 input().split() 的功能是将空格分隔的若干输入生成一个列表(list)。如下所示:

python 复制代码
>>> ls=input().split()
5 6 8 9
>>> type(ls)
<class 'list'>
>>> ls
['5', '6', '8', '9']
>>> 

代码二:需预先输入 n 的值
(1)使用 list 与 map:list(map(int,input().split()))

python 复制代码
n=eval(input())
ls=list(map(int,input().split()))
sum=0
for x in ls:
    sum+=x
print(sum)

'''
in:
5
5 3 1 2 9

out:
20
'''

(2)使用 input().split()

python 复制代码
n=int(input())
ls=[int(x) for x in input().split()]
print(sum(ls))

'''
in:
5
5 3 6 7 8

out:
29
'''

● 输入二维的用空格分隔的数据:list(map(int,input().split()))

python 复制代码
m,n=map(int,input().split())

ls=[]
for i in range(m):
    ls.append(list(map(int,input().split())))

print(ls)

'''
in:
3 5
1 2 3 4 5
5 4 3 2 1
6 7 8 9 0
out:
[[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [6, 7, 8, 9, 0]]
'''

【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/142204614
https://www.cnblogs.com/A180/p/15709850.html

相关推荐
CodeCraft Studio5 分钟前
借助Aspose.HTML控件,在 Python 中将 HTML 转换为 Markdown
开发语言·python·html·markdown·aspose·html转markdown·asposel.html
悠哉悠哉愿意24 分钟前
【电赛学习笔记】MaxiCAM 项目实践——与单片机的串口通信
笔记·python·单片机·嵌入式硬件·学习·视觉检测
封奚泽优29 分钟前
使用Python实现单词记忆软件
开发语言·python·random·qpushbutton·qtwidgets·qtcore·qtgui
Goona_1 小时前
拒绝SQL恐惧:用Python+pyqt打造任意Excel数据库查询系统
数据库·python·sql·excel·pyqt
xw33734095642 小时前
彩色转灰度的核心逻辑:三种经典方法及原理对比
人工智能·python·深度学习·opencv·计算机视觉
倔强青铜三2 小时前
为什么 self 与 super() 成了 Python 的永恒痛点?
人工智能·python·面试
墨尘游子2 小时前
目标导向的强化学习:问题定义与 HER 算法详解—强化学习(19)
人工智能·python·算法
小白学大数据3 小时前
基于Python的新闻爬虫:实时追踪行业动态
开发语言·爬虫·python
freed_Day3 小时前
python面向对象编程详解
开发语言·python
普郎特4 小时前
张三:从泥水匠到包工头的故事 *—— 深入浅出讲解 `run_in_executor()` 的工作原理*
python