繁体   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