使用ROWS行和COLS列创建名为A的二维数组。 ROWS和COLSS由用户在运行时指定。用[-10,99]范围内随机选择的整数填充A,然后重复执行以下步骤,直到文件结尾(1)输入整数x(2)在A(3)中搜索x,当x为在A中找到,输出找到x的坐标(row,col),否则输出消息“x not found!”
我需要帮助我想知道如何使用ROWS行和COLS列定义名为A的二维数组。 ROWS和COLSS由用户在运行时在python最新版本
中指定#--------------------------------------
#Hw 7
#E80
#---------------------------------------
A = [[Rows],[ColSS]] #I really dont know how to defend this part
for i in range (-10,99): #dont worry about this its just the logic not the actual code
x = int(input("Enter a number : "))
if x is found in A
coordinate row and clumn
otherwise output "x is not found"
答案 0 :(得分:2)
在Python中创建2D数组的惯用方法是:
rows,cols = 5,10
A = [[0]*cols for _ in range(rows)]
说明:
>>> A = [0] * 5 # Multiplication on a list creates a new list with duplicated entries.
>>> A
[0, 0, 0, 0, 0]
>>> A = [[0] * 5 for _ in range(2)] # Create multiple lists, in a list, using a comprehension.
>>> A
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> A[0][0] = 1
>>> A
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
请注意,您不希望创建重复的列表列表。它复制了列表引用,因此您有多个对相同列表的引用:
>>> A = [[0] * 5] * 2
>>> A
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> A[0][0] = 1
>>> A
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0]] # both rows changed!