Python返回字典 [英] Python return dictionary
问题描述
我正在尝试创建用户输入字典.该词典接受任何用户输入(例如"I like pie"),并将列出每个值及其相应的索引.但是,我的buildIndex函数不会返回在该函数内创建的字典.谁能提供一些关于为什么会发生这种情况的见解?
I am trying to create a dictionary of user input. This dictionary takes any user input (ex. "I like pie") and will list each value with its respective index. However, my buildIndex function will not return a the dictionary created within the function. Can anyone give some insight as to why this might be happening?
d = {}
def buildIndex(m):
m = m.lower()
words = m.split()
i = 0
while i < len(words):
nextWord = words[i]
if nextWord in d:
ref = [d[nextWord]]
ref.append(i)
d[nextWord] = ref
else:
d[nextWord] = i
i += 1
return d
推荐答案
您似乎正在像使用C一样来进行处理.这是可以理解的,但是却使Python过于复杂.让我们考虑一些事情.
You seem to be approaching this as if it is C. That is understandable, but overcomplicating your Python. Let's consider just a few things.
立即覆盖输入变量:
Overwriting an input variable immediately:
def buildIndex(m, d):
d = {}
在Python中,我们不需要声明变量或为其留出空间.因此,可以更清楚地表示为:
In Python we don't need to declare variables or make room for them. So this is much more clearly expressed as:
def build_index(m):
d = {}
(您注意到我从functionName camelCase更改为underscore_naming,这很常见.CamelCase对于Python中的类名更常见.)
(You notice I changed from functionName camelCase to underscore_naming -- that is pretty common. CamelCase is more common for class names in Python.)
使用一个明确的迭代器变量:
Python具有 iterables 的概念.这意味着可以快速分配任何事物类型的对象:
Python has a concept of iterables. This means any list-of-things type object can be assigned on the fly:
while i < len(words):
nextWord = words[i]
成为:
for word in words:
if word in d:
# etc...
甚至:
for word in m.split():
# blahblah
覆盖过程中的内容:
请仔细考虑本节的工作.逐步解决它.
Consider carefully what this section is doing. Step through it in your head.
if nextWord in d:
ref = [d[nextWord]]
ref.append(i)
d[nextWord] = ref
else:
d[nextWord] = i
您的词典的目的是什么?建立字数统计?在输入字符串中保留位置字典吗?...?!?实际上,这似乎没有做任何特别有用的事情.即使这样做,为什么在某些地方可以有一个列表值而在另一些地方可以有一个非列表整数值呢?选择一种类型并坚持使用它-这样会使事情变得简单得多.
What is the purpose of your dictionary? Build a word count? Keep a dictionary of locations-within-the-input-string? ...?!? As it is, this doesn't appear to do anything particularly useful. Even if it did, why it is OK to have a list value in some places and a non-list integer value in others? Pick a type and stick to it -- that will make things much easier.
您要寻求洞察力,而不是让任何人为您做功课-太酷了.请仔细考虑以上几点,然后阅读词典中的文档(有其中的函数将对您有很大帮助-尤其是 dict()
构造函数...).
You asked for insight, not for anyone to do your homework for you -- very cool. Consider the points above carefully, and read the docs on dictionaries (there are functions in there that will help you a lot -- particularly the dict()
constructor...).
您距离还不太远-只需减少一些Python习惯用法即可.
You're not too far off -- just need to get some Python idioms down.
这篇关于Python返回字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!