Python 计算行和列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40226729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count rows and columns
提问by Alan Wakke
How would I go about defining a fuctions in counting the number of rows and columns in a list of lists? For example group1 would be 1 row with 6 columns.
我将如何定义一个函数来计算列表列表中的行数和列数?例如 group1 将是 1 行 6 列。
group1 = [['.', 'A', 'A', '.', '.', '.']]
def num_rows(group):
def num_columns(group):
回答by Francisco Couzo
Just check the first index:
只需检查第一个索引:
def num_rows(group):
return len(group)
def num_columns(group):
return len(group[0])
Take in mind this will raise an IndexError
exception if there's no rows.
请记住,IndexError
如果没有行,这将引发异常。
回答by Barmar
he number of rows is the number of elements in the main list, and the number of columns is the number of elements in one of the elements. len()
returns the number of elements in a list.
行数是主列表中的元素数,列数是其中一个元素中的元素数。len()
返回列表中元素的数量。
rows = len(group1)
columns = len(group1[0])
回答by Sysad85
try using print(group1.shape), works for me
尝试使用打印(group1.shape),对我有用