作者paulluopaull (ppoo)
看板Python
标题[问题] 关於重复搜寻
时间Wed Aug 23 07:15:29 2017
小弟最近在做PYTHON习题
Problem
Given: A string ss of length at most 10000 letters.
Return: The number of occurrences of each word in ss, where words are
separated by spaces. Words are case-sensitive, and the lines in the output
can be in any order.
Sample Dataset:
We tried list and we tried dicts also we tried Zen
Sample Output:
and 1
We 1
tried 3
dicts 1
list 1
we 2
also 1
Zen 1
但是小弟做同样练习时会重复出现有重复的字:
we 3 -------1st occured
tried 3-------1st occured
list 1
and 1
we 3-------2nd occured
tried 3-------2nd occured
dicts 1
also 1
we 3------3rd occured
tried 3------3rd occured
zen 1
以下为小弟的CODE,再请各位大大帮忙检视一下问题出在哪里了。谢谢!
lines = 'We tried list and we tried dicts also we tried Zen'
for word in lines.lower().split(' '):
pare = {word: lines.lower().count(word)}
pare.update(pare) #希望用update消除重复项
for k1, v1 in pare.items():
print(k1, v1)
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 96.224.226.89
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1503443731.A.CF0.html
1F:→ wennie0433: word那个回圈每次都会重制你的pare所以根本没纪录到 08/23 11:19
2F:→ wennie0433: 回圈外面宣告一个dup = dict() 08/23 11:25
3F:→ wennie0433: 然後dup.update(pare) 08/23 11:25
4F:→ wennie0433: 最後那个回圈就直接搬出来不要在回圈里面pare换成dup 08/23 11:26
5F:→ wennie0433: 然後他题目大小写应该市分开算lower()要拿掉 08/23 11:27
6F:→ zerof: {k: lines.count(k) for k in set(lines.split())} 08/24 10:35