why print out wrong result. python enumerate, counter -
# -*- coding: utf-8 -*- collections import counter import itertools, collections listea=['it', 'was', 'the', 'besttttttttttttttrtrtrtrtrttrtr', 'of', 'times', 'it', 'was', 'the', 'worst', 'of', 'times', 'it', 'was', 'the', 'age', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx' 'of', 'wisdom', 'it', 'was', 'the', 'age', 'of', 'xx' 'foolishness'] index = collections.defaultdict(list); value, key in enumerate(listea): index[key].append(value) key1,value1 in index.items(): if len(value1)>=4: print value1
output not correct. problem code. output seems
[0, 6, 12, 27] [16, 17, 18, 19, 20, 21, 22, 23, 24] [2, 8, 14, 29] [1, 7, 13, 28]
i add number read easy listea=[0'it', 1'was', 2'the', 3'besttttttttttttttrtrtrtrtrttrtr', 4'of', 5'times', 6'it', 7'was', 8'the', 9'worst', 10'of', 11'times', 12'it', 13'was', 14'the', 15'age', 16'xx', 17'xx', 18'xx', 19'xx', 20'xx', 21'xx', 22'xx', 23'xx', 24'xx', 25'xx' 26'of', 27'wisdom', 28'it', 29'was', 30'the', 31'age', 32'of', 33'xx' 34'foolishness']
you're missing commas @ end of lines make list.
since list items string literals, end 2 items next each other no syntax between them. little known feature in python adjacent string literals concatenated. "foo" "bar"
same string "foobar"
. can span newlines too, long newline doesn't end expression (usually because it's inside parentheses or brackets of kind).
the issue means you'll have "xxof"
, "xxfoolishness"
in data, rather separate "xx"
(twice), "of"
, "foolishness"
strings. may throw off expected count.
to fix issue, add commas @ end of lines they've been missed:
listea=['it', 'was', 'the', 'besttttttttttttttrtrtrtrtrttrtr', 'of', 'times', 'it', 'was', 'the', 'worst', 'of', 'times', 'it', 'was', 'the', 'age', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', # add comma here 'of', 'wisdom', 'it', 'was', 'the', 'age', 'of', 'xx', # , here 'foolishness']
in addition commas, added newline break longest line @ at earlier point whole thing more fit on screen @ once (with no horizontal scroll bar). pep 8 recommends lines of code no longer 79 characters long, or 72 characters docstrings , comments can rearranged in way want. that's strict requirement code contributed python (e.g. fixes standard library), many people try follow pep 8 in own code, , many other python style guides have length limits (though they're bit more generous exact number of characters).
Comments
Post a Comment