Python中的二維列表(例項)

2021-08-21 12:19:07 字數 4297 閱讀 2481

1. 使用輸入值初始化列表

nums =

rows =

eval

(input("請輸入行數:"))

columns =

eval

(input("請輸入列數:"))

forrow

inrange

(rows)

:

nums.

()

forcolumn

inrange

(columns)

:

num =

eval

(input("請輸入數字:"))

nums[row].

(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

)

forrow

inrange

(rows)

:

numslist.

()

forcolumn

inrange

(columns)

:

num = random.

randint

(0, 9

)

numslist[row].

(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:

forj in i:

total +=

jprint

(total)

輸出結果為:

total =  59

4. 按列求和

nums =

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

total =

0for

column

inrange(

len(nums[

0])):

# print

( "column = "

,column)

fori in

range(

len(nums)):

total += nums[i][column]

print

(total)

輸出結果為:

1534

59

5. 找出和 最大的行

nums = [[

1, 2

, 3

], [

4, 5

, 6

], [

7, 8

, 9

], [

3, 4

, 7

]]

maxrow =

sum(nums[0

])

indexofmaxrow =

0for

row

inrange

(1, len(nums)

):

ifsum

(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

]]

forrow

inrange

(len(nums)

):

forcolumn

inrange

(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二維列表

class vector2 向量 def init self,x 0,y 0 self.x x self.y y 將函式轉移到類中,就是靜態方法 staticmethod 向右取值 defright return vector2 0,1 向上取值 staticmethod defup return ...

python二維列表排序

假設有乙個學生列表儲存了學號,姓名,年齡資訊 students 3,jack 12 2,rose 13 1,tom 10 5,sam 12 4,joy 8 按學號順序排序 sorted students,key lambda x x 0 1,tom 10 2,rose 13 3,jack 12 4,...

Python與二維列表

列表中的元素還可以是另乙個列表,這種列表稱為多為列表。只有一層巢狀的多維列表稱為二維列表。語法 變數 元素1,元素2 元素1,元素2 使用列表儲存員工的工號 姓名和月薪資訊 使用for迴圈遍歷輸出所有的員工資訊 employee infos a1 王保華 10000 a2 李維新 5200 a3 張...