利用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

相关推荐
梨轻巧35 分钟前
Maya Python基础: 类属性 VS 实例属性、实例方法、类方法、静态方法
python·maya
江塘1 小时前
机器学习-KNN算法实战及模型评估可视化(C++/Python实现)
开发语言·c++·人工智能·python·算法·机器学习
优秘UMI1 小时前
智能科技的附加特性:提升用户体验的多样选择
python·科技·其他·ai
蓝博AI1 小时前
基于卷积神经网络的汽车类型识别系统,resnet50,vgg16,resnet34【pytorch框架,python代码】
人工智能·pytorch·python·神经网络·cnn
麦麦大数据2 小时前
F039 python五种算法美食推荐可视化大数据系统vue+flask前后端分离架构
python·算法·vue·推荐算法·美食·五种算法
喆星时瑜2 小时前
ComfyUI本地部署Stable Diffusion:核心组件(Python、PyTorch、CUDA)版本与显卡配置全指南
pytorch·python·stable diffusion
大佬,救命!!!2 小时前
定时打印的练习整理
linux·服务器·python·学习笔记·学习方法·定时发送
南棱笑笑生2 小时前
20251028在荣品RD-RK3588-MID开发板的Android13系统下解决关机的时候最近打开的应用不关的问题
开发语言·python·rockchip
红树林073 小时前
BeautifulSoup 的页面中需要获取某个元素的 xpath 路径
前端·python·网络爬虫·beautifulsoup
jieyu11193 小时前
Python 实战:Web 漏洞 Python POC 代码及原理详解(1)
python·web安全