簡體   English   中英

計算以列表中相同項目開頭的列表數

[英]Count the number of lists that starts with the same item in a list

所以我有一個列表:

result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]]

我想要一個函數,它返回以變量"n"開頭(index[0])的列表數。 所以,如果n = '1'我在這種情況下得到 2 ,如果n = '2' I get 1

編輯:我已經嘗試了一些這樣的事情,但無法得到任何工作。

def Count(list,n):
result = []
value = 0
for i in list:
    if str(i[0]) == n:
        value = value + 1
        sum.append[value]
return len(sum)

print Count(result,1)

由於所有列表的長度相同,您可以執行以下操作:

import itertools

result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]]

res=list(itertools.chain.from_iterable(result))

res[0::4].count('1')
# prints 2
res[0::4].count('2')
#prints 1

首先,您使用itertools.chain扁平化列表列表(如果您有大量列表,這將非常有效;否則簡單的列表理解可能會更快),然后您獲得每個子列表的第一個元素並計算某個特定對象的頻率字符串存在。

您編寫的更正函數:

result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]]

def Count(myList,n):

    value = 0
    for i in myList:
        if i[0] == str(n):
            value = value + 1               

    return value

print Count(result,2)

不要將單詞list用作參數/變量名稱。 由於您實際上傳遞了一個數字,因此您必須將n轉換為字符串(子列表中的元素已經是字符串); 根本不需要帶有sum.append的行。

result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]]
lst2 = [item[0] for item in result]
lst2.count("1")

result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]]

def Count(myList,n):
    lst2 = [item[0] for item in myList]
    return lst2.count(str(n))

print Count(result,1) #prints 2
print Count(result,2) #prints 1

這是給你最簡單的答案。 你的老師永遠不會相信你寫的,對不起。

def f(n, lists):
    return len(filter(lambda l: l[0] == n, lists))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM