跳转到内容

数据结构基础:数组

来自维基教科书,开放世界中的开放书籍

试卷 1 - ⇑ 数据结构基础 ⇑

← 数据结构 数组 字段记录和文件 →


数组是索引相关的元素集。当我们想存储多个相同类型的数据时,我们可以使用数组而不是使用多个变量。您可以将数组视为数据项或元素列表,每个元素都有一个数字或索引,以便您可以引用每个项目。注意,数组的索引0开始

许多类似的变量 一个数组

name0=Alice
name1=Bob
name2=Claire
name3=Dan
name4=Eve

姓名
0 Alice
1 Bob
2 Claire
3 Dan
4 Eve

在大多数语言中,必须声明数组。这会设置数组中元素的数量以及元素的数据类型。这将为数组保留内存空间,然后再填充数据。Python 使用列表代替数组。列表更灵活,不需要初始化,但仍然可以执行此步骤,以使您的意图和代码更容易理解。

VB.NET Python
Dim names(0 To 4) As String
names(0) = "Alice"
names(1) = "Bob"
names(2) = "Claire"
names(3) = "Dan"
names(4) = "Eve"
names = ["" for x in range(5)]
names[0] = "Alice"
names[1] = "Bob"
names[2] = "Claire"
names[3] = "Dan"
names[4] = "Eve"

这也可以在一行代码中完成,在一步骤中初始化和填充数组。

VB.NET Python
Dim names() As String = {"Alice","Bob","Claire","Dan","Eve"}
names = ["Alice","Bob","Claire","Dan","Eve"]

数组索引

[编辑 | 编辑源代码]

我们可以使用索引访问数组中的单个元素。这在数组名称后用括号或方括号写出。要从我们的姓名数组中访问 Eve,我们将使用:

VB.NET Python
console.WriteLine(names(4))
print(names[4])

一些编程语言从 1 开始对数组编号,另一些从 0 开始。在我们上面的示例中,哪个数字与哪个人无关,因此使用 0 作为起点,但如果我们存储月份,许多人可能更喜欢将 1 月存储在 months[1] 而不是 months[0] 中。 XKCD 关于数组索引

练习:一维数组

声明一个数组,列出动物园中的 5 只动物(土豚、熊、杜鹃、鹿、大象),按字母顺序排列。

答案

VB.NET Python
dim zooanimals() as string = {"aardvark","bear","cow","deer","elephant"}
zooanimals = ["aardvark","bear","cow","deer","elephant"]

编写代码以输出第一只和最后一只动物。

答案

VB.NET Python
console.writeline(zooanimals(0))
console.writeline(zooanimals(4))
print(zooanimals[0]
print(zooanimals[4]

有人不小心吃掉了杜鹃,让用户添加一个新的第三只动物并将其全部打印出来。

   代码输出

插入新的第三只动物:鳄鱼
1: 土豚
2: 熊
3: 鳄鱼
4: 鹿
5: 大象

答案

VB.NET Python
console.write("Insert new third animal:")
zooanimals(2) = console.readline()
console.writeline("1: " & zooanimals(0))
console.writeline("2: " & zooanimals(1))
console.writeline("3: " & zooanimals(2))
console.writeline("4: " & zooanimals(3))
console.writeline("5: " & zooanimals(4))
''Alternatively an A-grade student might write:
for x = 0 to 4
  console.writeline(x + 1 & ": " & zooanimals(x))
next
zooanimals[2] = input("Insert new third animal: ")
print("1:",zooanimals[0])
print("2:",zooanimals[1])
print("3:",zooanimals[2])
print("4:",zooanimals[3])
print("5:",zooanimals[4])

#Alternatively an A-grade student might write:
for x in range(5):
 print(x,": ",zooanimals[x],sep="")

二维数组

[编辑 | 编辑源代码]

数组是索引相关的元素集。如果每个元素本身都是一个数组,那么我们就有一个二维 (2d) 数组。
如果我们将数组视为列表,我们可以将 2d 数组视为网格或矩阵。
大多数主要的编程语言允许您使用二维数组。它们的工作方式与一维数组非常相似,但允许您指定一个列索引一个行索引。

将 2D 数组视为网格,单元格的位置如上所示

我们可以创建上面所示的二维数组并通过执行以下操作分配值

VB.NET Python
Dim grid(4,4) As String
grid(0,3) = "A"
grid(3,2) = "B"
grid(1,4) = "C"
Console.Writeline("The content of 3,2 is:" & grid(3,2))
grid = [["" for x in range(4)] for x in range(4)] 
grid[0][3] = "A"
grid[3][2] = "B"
grid[1][4] = "C"
print("The content of 3,2 is:",grid[3][2])
代码也会输出值 B
示例:二维数组

二维数组非常有用,一个好的起点是创建您自己的《战舰》游戏版本,带有 4 个单元格乘 4 个单元格的网格。看看您是否能赢、打破它,或者更好的是,改进它!
我们使用二维 board 变量对以下棋盘进行建模

0 1 2 3
0 x o o o
1 o o x o
2 o o o o
3 o o o o
VB.NET Python
Dim x, y As Integer
Dim board(3, 3) As Char
board(0, 0) = "x"
board(0, 1) = "o"
board(0, 2) = "o"
board(1, 0) = "o"
board(1, 1) = "o"
board(1, 2) = "x"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"
For z = 1 To 3
Console.WriteLine("This is guess number " & z)
Console.Write("please insert your x location:")
x = Console.ReadLine()
Console.Write("please insert your y location:")
y = Console.ReadLine()
If board(x, y) = "x" Then
Console.WriteLine("you win!")
End If
Next
board = [["" for x in range(3)] for x in range(3)] 
board[0][0] = "x"
board[0][1] = "o"
board[0][2] = "o"
board[1][0] = "o"
board[1][1] = "o"
board[1][2] = "x"
board[2][0] = "o"
board[2][1] = "o"
board[2][2] = "o"
board[2][0] = "o"
board[2][1] = "o"
board[2][2] = "o"
for z in range(1,4):
    print("This is guess number", z)
    x = int(input("please insert your x location: "))
    y = int(input("please insert your y location: "))
    if board[x][y] == "x":
        print("you win!")
练习:二维数组
声明一个数组,用 char 类型创建一个 3 平方乘 3 平方的小型跳棋棋盘

答案

VB.NET Python
dim checkBoard(3,3) as char 'also checkBoard(2,2)
checkBoard = [["" for x in range(3)] for x in range(3)]
使用 b 表示黑色,w 表示白色,创建一个棋盘格图案。

答案

VB.NET Python
 checkBoard(1, 1) = "b"
 checkBoard(1, 2) = "w"
 checkBoard(1, 3) = "b"
 checkBoard(2, 1) = "w"
 checkBoard(2, 2) = "b"
 checkBoard(2, 3) = "w"
 checkBoard(3, 1) = "b"
 checkBoard(3, 2) = "w"
 checkBoard(3, 3) = "b"
 checkBoard[0][0] = "b"
 checkBoard[0][1] = "w"
 checkBoard[0][2] = "b"
 checkBoard[1][0] = "w"
 checkBoard[1][1] = "b"
 checkBoard[1][2] = "w"
 checkBoard[2][0] = "b"
 checkBoard[2][1] = "w"
 checkBoard[2][2] = "b"

一种更智能的方法是使用循环,这将允许您快速创建任何大小的棋盘。有一个问题将要求您构建它!请注意,在 python 中,我们被迫从 0 开始索引。此外,python 对字符和字符串使用相同的数据类型。

编写一个子例程来显示此棋盘(提示:您需要循环),该子例程将 checkBoard 作为参数。

答案

VB.NET Python
sub display(checkBoard())
for x = 1 to 3
   for y = 1 to 3
      console.write(checkBoard(x,y))
   Next
   console.writeline()
Next
def display(checkBoard):
    for x in range(3):
        for y in range(3):
            print(checkBoard[x][y],end="")
        print()

声明一个 chessBoard(8*8 个方格),用 b 表示黑色,w 表示白色,以编程方式对其进行着色。您可能想在上面的棋盘格颜色分配中寻找一个模式,并与MOD 函数交朋友。

您也可能想在尝试回答这个问题时变得有点循环

答案

VB.NET Python
dim chessBoard(8,8) as char 'also chessBoard(7,7)
for x = 1 to 8
   for y = 1 to 8
      if (x + y) MOD 2 = 1 then
         chessBoard(x,y) = "w"
      else
         chessBoard(x,y) = "b"
      end if
   next
next
display(chessBoard()) ' using a slightly updated version of the subroutine display()
chessBoard = [["" for x in range(8)] for x in range(8)]
for x in range(8):
   for y in range(8):
      if (x + y) % 2 == 1:
         chessBoard[x][y] = "w"
      else:
         chessBoard[x][y] = "b"
display(chessBoard) # using a slightly updated version of the subroutine display()

如果您完成了这项工作,您可能想让程序打印一些巨大的棋盘,无论什么能使您兴奋。

使用以下二维数组,grid(4,4)

  • 编写代码以输出名称 CRAIG
  • 在第 2 行(第三行)插入 MARY
  • SAM 覆盖 STEVE

答案

VB.NET Python
Console.Writeline(grid(3,0) & grid(3,1) & grid(3,2) & grid(3,3) & grid(3,4))
grid(2,0) = "M"
grid(2,1) = "A"
grid(2,2) = "R"
grid(2,3) = "Y"
grid(1,0) = "S" ' you could skip this
grid(1,1) = "A" 
grid(1,2) = "M"
grid(1,3) = ""
grid(1,4) = ""
print(grid[3][0] + grid[3][1] + grid[3][2] + grid[3][3] + grid[3][4])
grid[2][0] = "M"
grid[2][1] = "A"
grid[2][2] = "R"
grid[2][3] = "Y"
grid[1][0] = "S" # you could skip this
grid[1][1] = "A" 
grid[1][2] = "M"
grid[1][3] = ""
grid[1][4] = ""
华夏公益教科书