天天看點

python二維清單添加_python中的二維清單執行個體詳解

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 random

numsList = []

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 = 0

for i in nums:

for j in i:

total += j

print(total)

輸出結果為:

total = 59

4. 按列求和

nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 4, 7]]

total = 0

for column in range(len(nums[0])):

# print("column = ",column)

for i in range(len(nums)):

total += nums[i][column]

print(total)

輸出結果為:

15

34

59

5. 找出和 最大的行

nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 4, 7]]

maxRow = sum(nums[0])

indexOfMaxRow = 0

for row in range(1, len(nums)):

if sum(nums[row]) > maxRow:

maxRow = sum(nums[row])

indexOfMaxRow = row

print("索引:",indexOfMaxRow)

print("最大的行:",maxRow)

輸出結果為:

索引: 2

最大的行: 24

6. 打亂二維清單的所有元素

import random

nums = [[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]]

補充:下面給大家介紹下python 二維清單按列取元素。

直接切片是不行的:

>>> a=[[1,2,3], [4,5,6]]

>>> a[:, 0] # 嘗試用數組的方法讀取一列失敗

TypeError: list indices must be integers or slices, not tuple

我們可以直接構造:

>>> b = [i[0] for i in a] # 從a中的每一行取第一個元素。

>>> print(b)

[1, 4]

總結

以上所述是小編給大家介紹的python中的二維清單執行個體詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對腳本之家網站的支援!