1. 使用输入值初始化列表
1 2 3 4 5 6 7 8 9 |
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)
|
2. 使用随机数初始化列表
1 2 3 4 5 6 7 8 9 10 11 |
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)
|
3. 对所有的元素求和
1 2 3 4 5 6 |
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)
|
4. 按列求和
1 2 3 4 5 6 7 |
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)
|