不同的输入:
1.分别传入两个数组
n = int(input())
arr1 = []
arr2 = []
for i in range(n):
a,b = map(int,input())
arr1.append(a)
arr2.append(b)
2.自定义数组大小并传入数据
一维情况:
N = 1010
n = int(input())
nums = [0] * N
nums[1:n+1] = (int(x) for x in input().split())
二维情况-行数未知:
import sys
matrix = [[int(x) for x in line.split()] for line in sys.stdin]
二维情况-行数已知:
n = int(input()
matrix = [[int(x) for x in input().xplit()] for _ in range(x)]
二维情况-行数已知-但是每行输入的数据个数未知:
n = int(input())
nums = []
for _ in range(n):
nums.extend(map(int,input().split()))
# 或nums.extend(int(x) for x in input().split())
3..txt文件读取
with open ("data.txt", "r", encoding = "utf-8") as f:
matrix = [list(map(int, line.strip().split())) for line in f]
# 或 matrix [list(int(x) for x in line.strip().split()) for line in f]
4..对读取的数据进行简单处理
# 读取所有行(假设行数未知)
import sys
matrix = [[int(num) + 1 for num in line.split()] for line in sys.stdin]
# 或已知行数(例如首行为行数)
n = int(input().split()[0]) # 假设第一行是行数
matrix = [[int(num) + 1 for num in input().split()] for _ in range(n)]
for循环:
在for循环内部对i进行修改,仅仅只会影响此次迭代中的i,在下一次迭代时,会被强制更新为迭代器的下一个值。
(1)不影响循环遍历:for 循环的迭代次数和顺序由迭代器(如 range)固定,循环内修改 i 不会改变遍历逻辑。
(2)仅影响当前迭代:修改 i 的值仅在当前循环体内有效,下一次迭代时 i 会被强制更新为迭代器的下一个值。
如果想要通过改变i来控制循环,可以使用while循环,比如:
i = 0
while i < 10:
if i == 2:
i += 1 # 跳过 2
print(i)
i += 1
排序:
# 二维数组针对某一列进行排序
data = [
[3, 9, 5],
[1, 2, 4],
[4, 6, 7]
]
sorted_list = sorted(data,key = lambda x:x[1]) #按照第二行排序
# 或使用以下代码对二维数组的自身进行排序
data.sort(key = lambda x : x[1])
# 降序排列
sorted_data = sorted(data, key=lambda x: x[1], reverse=True)
# 或
data.sort(key=lambda x: x[1], reverse=True)
#按照第二行的绝对值排序
data = [
[5, -3],
[2, 8],
[1, -10]
]
sorted_data = sorted(data,key = lambda x: abs(x[1]))
# 按第1列字符串长度升序排序
data = [
["apple", 100],
["banana", 200],
["cherry", 50]
]
sorted_data = sorted(data, key=lambda x: len(x[0]))
# 按两列乘积升序排序
data = [
[3, 4],
[2, 5],
[1, 6]
]
sorted_data = sorted(data, key=lambda x: x[0] * x[1]))
确定日期的正确性:
def check(date):
year = date // 10000
month = (date % 10000) // 100
day = date % 100
#对year的错误判断
#对month的错误判断
if month == 0 or month > 12:
return False
#对day的错误判断,分为月份不为2和月份为2的判断
if month != 2 and day > months[month - 1]:
return False
if month == 2:
leap = ( year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
if day > 28 + leap or day == 0:
return False
return True