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

相关推荐
ZH15455891319 分钟前
Flutter for OpenHarmony Python学习助手实战:面向对象编程实战的实现
python·学习·flutter
玄同76510 分钟前
SQLite + LLM:大模型应用落地的轻量级数据存储方案
jvm·数据库·人工智能·python·语言模型·sqlite·知识图谱
User_芊芊君子15 分钟前
CANN010:PyASC Python编程接口—简化AI算子开发的Python框架
开发语言·人工智能·python
白日做梦Q26 分钟前
Anchor-free检测器全解析:CenterNet vs FCOS
python·深度学习·神经网络·目标检测·机器学习
喵手40 分钟前
Python爬虫实战:公共自行车站点智能采集系统 - 从零构建生产级爬虫的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集公共自行车站点·公共自行车站点智能采集系统·采集公共自行车站点导出csv
喵手1 小时前
Python爬虫实战:地图 POI + 行政区反查实战 - 商圈热力数据准备完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·地区poi·行政区反查·商圈热力数据采集
熊猫_豆豆1 小时前
YOLOP车道检测
人工智能·python·算法
nimadan121 小时前
**热门短剧小说扫榜工具2025推荐,精准捕捉爆款趋势与流量
人工智能·python
默默前行的虫虫1 小时前
MQTT.fx实际操作
python
YMWM_1 小时前
python3继承使用
开发语言·python