【问题标题】:python list counting elementspython列表计数元素
【发布时间】:2016-02-26 03:15:13
【问题描述】:

我有如下代码

如何发现 abc 是由列表组成的列表?

我的地图功能有什么问题?

我希望我的函数返回输入列表中每个元素的计数除以列表的长度。

类似

{'brown': 0.16666666666666666, 'lazy': 0.16666666666666666, 'jumps': 0.16666666666666666, 'fox': 0.16666666666666666,  'dog': 0.16666666666666666, 'quick': 0.16666666666666666}

我的代码:

quickbrownfox1=['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']
print quickbrownfox1


def tf(tokens):
   
    abc=([[x,(tokens.count(x))] for x in set(tokens)])
    print type(abc)#how to know that abc is made up of lists
    print type(abc[1])
    answer=abc.map(lambda input:(input(0)),input(1)/len(tokens)))
    
    return answer
    #return <FILL IN>

print tf((quickbrownfox1)) # Should give { 'quick': 0.1666 ... }
#print tf(tokenize(quickbrownfox)) # Should give { 'quick': 0.1666 ... }

_______________________________________

更新 1

我更新了我的代码如下。我得到结果[('brown', 0), ('lazy', 0), ('jumps', 0), ('fox', 0), ('dog', 0), ('quick', 0)] 知道为什么吗?如果我做return return list(map(lambda input: (input[0], input[1]), abc)),它会给出正确的结果 - [('brown', 1), ('lazy', 1), ('jumps', 1), ('fox', 1), ('dog', 1), ('quick', 1)]

from __future__ import division
quickbrownfox1=['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']

def islistoflists(i):
    if isinstance(i, list):
        if len(i) > 0 and all(isinstance(t, list) for t in i):
            return True
    return False


def tf(tokens):

    print(islistoflists(tokens))

    abc = ([[x,tokens.count(x)] for x in set(tokens)])
    return list(map(lambda input: (input[0], input[1] / len(tokens)), abc))

print tf(quickbrownfox1)

更新 2

我正在使用 pyspark/spark。这可能是我在 update1 中遇到问题的原因吗?

【问题讨论】:

  • is a list made up of lists ?在 abc 上创建一个 for 循环,然后使用 type() 检查每个元素。如果所有这些都列出,那么你得到了你想要的。
  • map 是内置函数,不是方法,所以abc.map 不起作用,你必须使用map(function, abc)

标签: python list dictionary lambda


【解决方案1】:

计数器解决方案肯定会更好。您对tokens.count 的使用给出了代码二次时间复杂度。继承人您的代码已修复。请注意,map 是一个独立函数,而不是列表或任何其他类型的成员函数。

from __future__ import division
quickbrownfox1=['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']

def islistoflists(i):
    if isinstance(i, list):
        if len(i) > 0 and all(isinstance(t, list) for t in i):
            return True
    return False


def tf(tokens):

    print(islistoflists(tokens))

    abc = ([[x,tokens.count(x)] for x in set(tokens)])
    return list(map(lambda input: (input[0], input[1] / len(tokens)), abc))

print tf(quickbrownfox1)

要测试您是否有一个列表列表,您可以使用isinstance 检查父对象的类型,如果它是一个列表并且其中至少包含一个元素,您可以使用isinstance 循环遍历它们检查每个子对象是否是一个列表。

请注意,我让您的函数返回一个元组列表,暗示这些项目是只读的,但您可以通过更改行使其返回一个列表列表。

return list(map(lambda input: [input[0], input[1] / len(tokens)], abc))

如果您仔细观察,您会发现一组括号已被替换为方括号,从而使每个元素成为一个列表。

如果您有不支持 from __future__ import division 导入的较旧版本的 python 2,您可以使用以下解决方法来强制进行浮点除法。

return list(map(lambda input: (input[0], (input[1] * 1.0) / len(tokens)), abc))

【讨论】:

  • 我试过你的方法。当我使用list(map(lambda input: (input[0], int(input[1])/len(tokens) ), abc)) 时,我得到了答案[('brown', 0), ('lazy', 0), ('jumps', 0), ('fox', 0), ('dog', 0), ('quick', 0)]。我的 abc 是 [['brown', 1], ['lazy', 1], ['jumps', 1], ['fox', a], ['dog', 1], ['quick', 1]]
  • 我正在关注 MOOC 和 pyspark。不确定python版本!
  • 使用float(input[1])强制浮点除法。
【解决方案2】:

根据我认为您要问的内容,您可以做类似的事情

token_size = len(tokens)
word_counter_list = {}
for word in tokens:
    if word in word_counter_list:
        word_counter_list[word] += 1
    else:
        word_counter_list[word] = 1

for word, amount in word_counter_list:
    print("The word " + word + " was used " + str(amount/token_size)

话虽如此,问题不是很清楚,因为您提到了列表类型(),但显示了列表中词频的百分比

【讨论】:

    【解决方案3】:

    您应该可以使用Counter 轻松完成此操作:

    $ python3
    Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
    [GCC 4.9.1] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    @>>> from collections import Counter
    @>>> c = Counter(['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog'])
    @>>> total = sum(c.values())
    @>>> result = dict()
    @>>> for key, value in c.items():
    @...   result[key] = value/total
    @... 
    @>>> result
    {'dog': 0.16666666666666666, 'quick': 0.16666666666666666, 'fox': 0.16666666666666666, 'brown': 0.16666666666666666, 'jumps': 0.16666666666666666, 'lazy': 0.16666666666666666}
    

    或者,让它成为超级pythonic:

    dict([ (key, value/total) for key,value in c.items() ])
    

    【讨论】:

    猜你喜欢
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2022-12-18
    • 2014-02-15
    • 2011-05-07
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多