我有一个下面给出的单词列表(示例):
['the', 'counter', 'starts', 'the', 'starts', 'for']
Run Code Online (Sandbox Code Playgroud)
我想按顺序处理这个列表并生成一个pair (x,y)x随每个单词递增而y只有在看到一个唯一的单词时才会递增.因此,对于给定的示例,我的输出应该是:
[(1,1) (2,2), (3,3) (4,3) (5,3) (6,4)]
我不确定如何在python中执行此操作.如果我能够获得有关如何做到这一点的一些见解,那将是很棒的.谢谢.
试试这个:
>>>from collections import Counter
>>>data = ['the', 'counter', 'starts', 'the', 'starts', 'for']
>>>tally=Counter()
>>>for elem in data:
>>> tally[elem] += 1
>>>tally
Counter({'starts': 2, 'the': 2, 'counter': 1, 'for': 1})
Run Code Online (Sandbox Code Playgroud)
从这里:http://docs.python.org/2/library/collections.html
当然,这导致字典不是列表.我不知道是否有任何方法可以将此dict转换为列表(如某些zip函数?)希望它对任何人都有帮助
>>> words = ['the', 'counter', 'starts', 'the', 'starts', 'for']
>>> uniq = set()
>>> result = []
>>> for i, word in enumerate(words, 1):
uniq.add(word)
result.append((i, len(uniq)))
>>> result
[(1, 1), (2, 2), (3, 3), (4, 3), (5, 3), (6, 4)]
Run Code Online (Sandbox Code Playgroud)
collections.Counter计数的出现:我很欣赏这不直接回答你的问题,但它提出了规范,pythonic的方式来计算东西作为对这个答案中提供的错误用法的回应.
from collections import Counter
data = ['the', 'counter', 'starts', 'the', 'starts', 'for']
counter = Counter(data)
Run Code Online (Sandbox Code Playgroud)
结果是一个类似dict的对象,可以通过键访问
counter['the']
>>> 2
Run Code Online (Sandbox Code Playgroud)
你也可以调用Counter.items()来生成(元素,计数)对的无序列表
counter.items()
>>> [('starts', 2), ('the', 2), ('counter', 1), ('for', 1)]
Run Code Online (Sandbox Code Playgroud)
你想要的输出有点奇怪,可能值得重新考虑为什么你需要那种格式的数据.
像这样:
>>> seen = set()
>>> words = ['the', 'counter', 'starts', 'the', 'starts', 'for']
>>> for x, w in enumerate(words, 1):
... seen.add(w)
... print(x, len(seen))
...
(1, 1)
(2, 2)
(3, 3)
(4, 3)
(5, 3)
(6, 4)
Run Code Online (Sandbox Code Playgroud)
在实际操作中,我将生成一个生成器函数来连续生成元组,而不是打印它们:
def uniq_count(lst):
seen = set()
for w in lst:
seen.add(w)
yield len(seen)
counts = list(enumerate(uniq_count(words), 1))
Run Code Online (Sandbox Code Playgroud)
请注意,我还将两个计数的逻辑分开.因为enumerate每对中的第一个数字只需要你,所以更容易处理生成器中的第二个数字,然后enumerate处理第一个数字.