pythonの2 Dリスト(インスタンス)

15727 ワード

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)

出力結果:
33123456789
[[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)

出力結果:
224

6.2 Dリストのすべての要素を乱す
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]]