当前位置: 首页 > news >正文

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

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

x=int(input())
print(x)

● 当 n=2 时:

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

● 当 n=3 时:

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()))

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()

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)。如下所示:

>>> 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()))

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 9out:
20
'''

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

n=int(input())
ls=[int(x) for x in input().split()]
print(sum(ls))'''
in:
5
5 3 6 7 8out:
29
'''

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

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


 


http://www.mrgr.cn/news/42671.html

相关文章:

  • ROS2(Robot Operating System 2)与树莓派(Raspberry Pi)
  • 基于拥堵模型的轻量级平台公交室内情况监控系统
  • Redis数据库与GO(二):list,set
  • C++教程一口气讲完!(万字讲解)♪(´▽`)上
  • 【Linux】进程地址空间、环境变量:从理论到实践(三)
  • 【Linux】-----进程第二弹(优先级,环境变量)
  • HAR笔记--事件相机(event camera)数据常见处理方法总结
  • 开源AI智能名片在打造人格化品牌平台中的应用:以抖音、快手、微博为例
  • csp-j模拟三补题报告
  • YouTube音视频合并批处理基于 FFmpeg的
  • 《Linux服务与安全管理》| 配置YUM源并验证
  • linux驱动:(21)ioctl接口(二)驱动与应用程序传递ioctl命令
  • 90后新生代女高音歌唱家李思思声乐大师课公益讲座即将开启
  • PyTorch实现卷积神经网络CNN
  • 生产消费者模式
  • 自动驾驶系列—颠覆未来驾驶:深入解析自动驾驶线控转向系统技术
  • 无IDEA不Java:快速掌握Java集成开发环境
  • 什么是 NVIDIA 机密计算?( 上篇 )
  • 一次解决Go编译问题的经过
  • vSAN01:vSAN简介、安装、磁盘组、内部架构与调用关系