python中的二维列表(实例)
来源:互联网 发布:tensorflow 路径规划 编辑:程序博客网 时间:2024/06/06 01:34
1. 使用输入值初始化列表
nums = []rows = eval(input("请输入行数:"))columns = eval(input("请输入列数:"))for row in range(rows): nums.append([]) for column in range(columns): num = eval(input("请输入数字:")) nums[row].append(num)print(nums)
输出结果为:
请输入行数:3请输入列数:3请输入数字:1请输入数字:2请输入数字:3请输入数字:4请输入数字:5请输入数字:6请输入数字:7请输入数字:8请输入数字:9[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2. 使用随机数初始化列表
import randomnumsList = []nums = random.randint(0, 9)rows = random.randint(3, 6)columns = random.randint(3, 6)for row in range(rows): numsList.append([]) for column in range(columns): num = random.randint(0, 9) numsList[row].append(num)print(numsList)
输出结果为:
[[0, 0, 4, 0, 7], [4, 2, 9, 6, 4], [7, 9, 8, 1, 7], [1, 7, 7, 5, 7]]
3. 对所有的元素求和
nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 4, 7]]total = 0for i in nums: for j in i: total += jprint(total)
输出结果为:
total = 59
4. 按列求和
nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 4, 7]]total = 0for column in range(len(nums[0])): # print("column = ",column) for i in range(len(nums)): total += nums[i][column] print(total)
输出结果为:
153459
5. 找出和 最大的行
nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 4, 7]]maxRow = sum(nums[0])indexOfMaxRow = 0for row in range(1, len(nums)): if sum(nums[row]) > maxRow: maxRow = sum(nums[row]) indexOfMaxRow = rowprint("索引:",indexOfMaxRow)print("最大的行:",maxRow)
输出结果为:
索引: 2最大的行: 24
6. 打乱二维列表的所有元素
import randomnums = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 4, 7]]for row in range(len(nums)): for column in range(len(nums[row])): i = random.randint(0, len(nums) - 1) j = random.randint(0, len(nums[row]) - 1) nums[row][column], nums[i][j] = nums[i][j], nums[row][column]print(nums)
输出结果为:
[[3, 3, 5], [7, 6, 7], [4, 2, 4], [9, 8, 1]]
7. 排序
'''sort方法,通过每一行的第一个元素进行排序。对于第一个元素相同的行,则通过它们的第二个元素进行排序。如果行中的第一个和第二个元素都相同,那么利用他们的第三个元素进行排序,依此类推'''points = [[4, 2], [1, 7], [4, 5], [1, 2], [1, 1], [4, 1]]points.sort()print(points)
输出结果为:
[[1, 1], [1, 2], [1, 7], [4, 1], [4, 2], [4, 5]]
阅读全文
0 0
- python中的二维列表(实例)
- 这里遇到的一个小坑-python中的二维列表
- python 将一维列表转二维列表
- [Python] 专题五.列表基础知识 二维list排序、获取下标和处理txt文本实例
- python中的二维数组
- 【python】列表实例1
- python字典列表实例
- python中二维列表的创建
- python中二维列表的创建
- Python 创建二维列表+追加元素+items()
- 关于Python的基础知识8--二维列表
- python 二维元祖关联合并 返回列表
- Python中的列表
- 5.1 Python中的列表
- Python中的列表反转
- python中的list列表
- python中的列表
- Python中的列表(上)
- Codeforces Gym 101158 A. Rearranging a Sequence
- 双向链表c语言实现 doublelinklist.h 和 doublelinklist.c
- c++ 析构函数调用时机
- 表单的使用(新手入门基础学习)
- Codeforces Gym 101158 B. Quality of Check Digits (模拟)
- python中的二维列表(实例)
- 【codeforces 749A】Bachgold Problem
- 单片机实验六
- C++动态规划之采药(openjudge)
- Codeforces Gym 101158 C. Distribution Center
- Java垃圾回收策略
- 优化Go的模式
- Java 异常中e的getMessage()和toString()方法的异同
- 面试OR笔试1——RNA嵌套