[英]How to get length of a list of lists in python
所以,如果我有一個名為myList的列表,我使用len(myList)
來查找該列表中的元素數。 精細。 但是如何在列表中找到列表的數量?
text = open("filetest.txt", "r")
myLines = text.readlines()
numLines=len(myLines)
print numLines
上面使用的文本文件有3行4個元素,用逗號分隔。 變量numLines打印為'4'而不是'3'。 因此, len(myLines)
返回每個列表中的元素數量而不是列表列表的長度。
當我打印myLines[0]
我得到第一個列表, myLines[1]
第二個列表,等等。但len(myLines)
沒有顯示列表的數量,這應該與'行數'相同。
我需要確定從文件中讀取多少行。
這會將數據保存在列表列表中。
text = open("filetest.txt", "r")
data = [ ]
for line in text:
data.append( line.strip().split() )
print "number of lines ", len(data)
print "number of columns ", len(data[0])
print "element in first row column two ", data[0][1]
“上面使用的文本文件有3行4個元素用逗號分隔。變量numLines打印為'4'而不是'3'。所以,len(myLines)返回每個列表中元素的數量而不是列表清單。“
聽起來你正在閱讀一個包含3行和4列的.csv。 如果是這種情況,您可以使用.split()方法找到行數和行數:
text = open("filetest.txt", "r").read()
myRows = text.split("\n") #this method tells Python to split your filetest object each time it encounters a line break
print len(myRows) #will tell you how many rows you have
for row in myRows:
myColumns = row.split(",") #this method will consider each of your rows one at a time. For each of those rows, it will split that row each time it encounters a comma.
print len(myColumns) #will tell you, for each of your rows, how many columns that row contains
如果列表的名稱是listlen
那么只需輸入len(listlen)
。 這將返回python中列表的大小。
方法len()返回列表中的元素數。
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
當我們運行上面的程序時,它會產生以下結果 -
第一個列表長度:3個第二個列表長度:2
你可以用reduce來做到:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [], [1, 2]]
print(reduce(lambda count, l: count + len(l), a, 0))
# result is 11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.