Python3中一维数组和二维数组的输入 您所在的位置:网站首页 python输入一个二维数组csdn Python3中一维数组和二维数组的输入

Python3中一维数组和二维数组的输入

2023-12-05 18:40| 来源: 网络整理| 查看: 265

python输入一维数组 使用int()进行强制类型转型 当输入内容不为数字时,不能转型,发生except跳出循环。 先声明data是一个list,将input_A一个个拼接(+)进去。

data = [] while True: try: input_A = int(input("Input: ")) data +=[input_A] except: break print(data) print(type(data)) print(type(data[0]))

运行代码,从键盘输入

E:\Anaconda3\python.exe D:/pycode/NowCooder/数组的输入.py Input: 1 Input: 2 Input: 3 Input: ; # 输入英文分号停止输入 [1, 2, 3]

python输入二维数组 正则表达式(r’[\D]’)会利用非数字的字符进行切割,因此数字之间插入什么都无所谓。

import re data2D = [] while True: userInput = input('Input:') # 输入数组,用空格隔开即可 info = re.split(r'[\D]', userInput) # 正则表达式分割 data = [] # 定义一维数组 try: for number in info: data += [int(number)] # 一维数组加入数字 data2D += [data] # 一维数组加入到二维中去 except: break print(data2D)

测试二维数组的输入 输入最后一行字符后,连续按两次Enter键结束输入

E:\Anaconda3\python.exe D:/pycode/NowCooder/数组的输入.py Input:1 2 3 Input:2,3,4 Input:1[2[3[4 Input:9-8-3-4 Input: [[1, 2, 3], [2, 3, 4], [1, 2, 3, 4], [9, 8, 3, 4]] Process finished with exit code 0

在Input:后按 Enter 停止输入

E:\Anaconda3\python.exe D:/pycode/NowCooder/数组的输入.py Input:1 2 3 Input: [[1, 2, 3]]

使用re.split来分割字符串 re.split(r’[\D]’, s) 表示将字符串 s 按“非数字”分割成一个列表,保留数字,去除非数字字符。

import re s = input() # abcd12345ed125ss123456789 ss = re.split(r'\D', s) sss = re.split(r'[\D]', s) # print(max(ss, key=len)) # 123456789 print(ss) # ['', '', '', '', '12345', '', '125', '', '123456789'] print(sss) # ['', '', '', '', '12345', '', '125', '', '123456789'] data = [] for num in ss: if num != '': data += [int(num)] # [ ] 不能省略 print(data) # [12345, 125, 123456789]

https://www.jianshu.com/p/d177f14a7d44 正则表达式 https://www.cnblogs.com/tina-python/p/5508402.html



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有