我想請問,我要計算list的內的字元數量
假設a=[['1', '1', '2', '2', '3'], ['4', '4'], ['1', '7', '9', '10'], ['6', '2'], ['3']]
我想要的出的結果是[5], [2], [4], [2], [1]
原本使用
sum(x.count('foobar') for x in a)
結果這是找特定字的QQ
再使用
print ("The list is : " + str(positive_result))
counter = 0
for i in positive_result:
counter = counter + 1
print ("Length of list using naive method is : " + str(counter))
得出的是5,是list的數量
而
def total_elements(list):
count = 0
for element in list:
count += 1
return count
print("The total number of elements in the list: ", total_elements(a))
也是一樣
後來想到要寫迴圈來計算
a1=[]
for b in a:
count=a.count(b)
print(a1)
也錯了
想請問大家如何可以解決,拜託拜託
#python2.7
a=[['1', '1', '2', '2', '3'], ['4', '4'], ['1', '7', '9', '10'], ['6', '2'], ['3']]
b = map(lambda x : len(x), a)
#python3
a=[['1', '1', '2', '2', '3'], ['4', '4'], ['1', '7', '9', '10'], ['6', '2'], ['3']]
b = list(map(lambda x : len(x), a))
a=[['1', '1', '2', '2', '3'], ['4', '4'], ['1', '7', '9', '10'], ['6', '2'], ['3']]
[len(x) for x in a]
[5, 2, 4, 2, 1]