简体   繁体   English

python带有行和列的二维数组

[英]python two dimensional array with rows and columns

Create a two-dimensional array named A with ROWS rows and COLS columns. 用ROWS行和COLS列创建一个名为A的二维数组。 ROWS and COLSS are specified by the user at run time. ROWS和COLSS由用户在运行时指定。 Fill A with randomly-chosen integers from the range [ -10,99 ], then repeatedly perform the following steps until end-of-file(1) input an integer x(2) search for x in A(3) when x is found in A, output the coordinate (row,col) where x is found, otherwise output the message "x not found!" 用[-10,99]范围内的随机选择的整数填充A,然后重复执行以下步骤,直到文件结尾(1)输入一个整数x(2)且当x为x时在A(3)中搜索x在A中找到,输出在其中找到x的坐标(row,col),否则输出消息“未找到x!”。

I need help I am wondering how can we define two-dimensional array named A with ROWS rows and COLS columns. 我需要帮助,我想知道我们如何定义带有AROWS行和COLS列的二维数组A。 ROWS and COLSS are specified by the user at runtime in python latest version 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"

The idiomatic way to create a 2D array in Python is: 在Python中创建2D数组的惯用方式是:

rows,cols = 5,10
A = [[0]*cols for _ in range(rows)]

Explanation: 说明:

>>> 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]]

Note you do not want to create duplicate lists of lists. 注意,您不想创建重复的列表列表。 It duplicates the list references so you have multiple references to the same list : 它复制了列表引用,因此您对同一列表有多个引用:

>>> 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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM