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

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]
<class 'list'>
<class 'int'>

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

猜你喜欢

转载自blog.csdn.net/s1162276945/article/details/82818496
今日推荐