变量名与字典?

发布于 2024-11-09 20:27:31 字数 566 浏览 0 评论 0原文

Python初学者在这里。一个关于字典的问题。

我的输入是一个可变长度列表(例如 a = ['eggs', 'ham', 'bacon'...] ),它充当要在导入的 CSV 文件上使用的搜索词列表。

我定义了四个函数,将每个术语与所述 CSV 文件中的各种值相匹配。因此,每个输入项将产生四个结果列表。

我想将输入项存储为字典中的键(足够简单),并将生成的四个列表存储为值(也足够简单)。

但是,因为输入列表的长度可变,所以我想设置一个函数来定义和命名词典“term1”、“term2”,基本如下所示:

term1 = { 'eggs' : [[list1] , [list2] , [list3] , [list4]] }
term2 = { 'ham' : [[list1] , [list2] , [list3] , [list4]] }
term3 = { 'bacon' : [[list1] , [list2] , [list3] , [list4]] }

是否有一种)像这样命名词典的方法? b) 它们是否在全球范围内可用?如果是这样,怎么办?非常感谢任何和所有的帮助。

Python beginner here. A question about dictionaries.

My input is a variable length list (eg a = ['eggs', 'ham', 'bacon'...] ) which functions as a list of search terms to be used on an imported CSV file.

I have defined four functions that match each term to various values from said CSV file. So, each input term will result in four lists of results.

I would like to store the input terms as a key in a dictionary (easy enough) and the resulting four lists as values (also easy enough).

However, because the input list is of variable length I would like to set up a function to define and name the dictionaries 'term1', 'term2', illustrated very basically thus:

term1 = { 'eggs' : [[list1] , [list2] , [list3] , [list4]] }
term2 = { 'ham' : [[list1] , [list2] , [list3] , [list4]] }
term3 = { 'bacon' : [[list1] , [list2] , [list3] , [list4]] }

Is there a) a way to name dictionaries like this?; and b) AND have them be globally available? If so, how? Any and all help very much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无人接听 2024-11-16 20:27:31

这不是我推荐的方法,但您可以将本地和全局命名空间作为字典访问;例如,您可以使用熟悉的 dict 接口将任意变量添加到这些名称空间:

>>> globals()['foo'] = 'bar'
>>> foo
'bar'
>>> locals()['spam'] = 'eggs'
>>> spam
'eggs'

但是您将遇到命名冲突。另外,代码的其余部分如何知道哪些全局变量包含您的结果?他们还必须进行间接查找!

您最好只使用包含结果的一个字典,并将其作为命名空间而不是全局命名空间。

Not an approach I'd recommend, but you can access both the local and global namespaces as dictionaries; e.g. you can add arbitrary variables to those namespaces using the familiar dict interface:

>>> globals()['foo'] = 'bar'
>>> foo
'bar'
>>> locals()['spam'] = 'eggs'
>>> spam
'eggs'

You will run into naming conflicts though. Also, how will the rest of your code know what global variables contain your results? They'll have to do indirect look-ups too!

You better just use one dictionary containing your results, and let that be the namespace instead of the global namespace.

是你 2024-11-16 20:27:31

您可以尝试这样的操作:

results = {}
for name in ['eggs', 'ham', 'bacon']:
   results[name] = (function1(name), function2(name), function3(name), function4(name),)

其中 functionX 是将从 CSV 文件或其他文件返回 listX 结果的函数。

在这里,您将在结果字典中看到如下内容:

results = { 
   'eggs' : (egg_list1, egg_list2, egg_list3, egg_list4), 
   'ham' : (ham_list1, ham_list2, ham_list3, ham_list4),
   'bacon' : (bacon_list1, bacon_list2, bacon_list3, bacon_list4),
}

You can try something like this :

results = {}
for name in ['eggs', 'ham', 'bacon']:
   results[name] = (function1(name), function2(name), function3(name), function4(name),)

where functionX are your functions that will return the listX result from CSV file or whatever.

Here you will have in the results dictionnary something like this :

results = { 
   'eggs' : (egg_list1, egg_list2, egg_list3, egg_list4), 
   'ham' : (ham_list1, ham_list2, ham_list3, ham_list4),
   'bacon' : (bacon_list1, bacon_list2, bacon_list3, bacon_list4),
}
A君 2024-11-16 20:27:31

以下是如何预初始化包含所有数据的一个字典:

a = "eggs bacon ham".split()
summary = dict((key,([],[],[],[])) for key in a)

for lineno,line in enumerate(csv_file):
    # first element in the line is assumed to be the key ("eggs", "bacon", etc.)
    key = line[0]
    # update the data values for this key
    summary[key][0].append(lineno)
    summary[key][1].append(something_else)
    # ... etc.

不过,我发现这种索引访问有点脆弱,并且更喜欢键控或属性访问。您的 4 个列表的硬编码列表可能会更好地表示为字典,甚至某些简单数据统计类的对象。

另外,我认为您的“鸡蛋”、“培根”和“火腿”列表会随着时间的推移而增加,因为您会在 CSV 文件中找到“煎饼”、“华夫饼”、“薯饼”等条目。最近,当我浏览数据文件或数据库表时,我越来越多地使用 defaultdict 来统计数据。 defaultdict 不需要预先定义我期望获得的键(并且当输入数据添加新值时必须自己更新列表),defaultdict 只是添加我定义的形式的新条目:

class Tally(object):
    def __init__(self):
        self.count = 0
        self.lines = []
        self.values = []

from collections import defaultdict
summary = defaultdict(Tally)

for lineno,line in enumerate(csv_file):
    # first element in the line is assumed to be the key ("eggs", "bacon", etc.)
    key = line[0]
    # update the data values for this key
    summary[key].count += 1
    summary[key].lines.append(lineno)
    summary[key].values.append(line[1])
    # ... etc.

defaultdict 为我节省了麻烦和重复的工作if key不在summarydict中:添加新条目...”开销,所以我的代码保持相当干净。

Here is how you might pre-initialize your one dictionary containing all data:

a = "eggs bacon ham".split()
summary = dict((key,([],[],[],[])) for key in a)

for lineno,line in enumerate(csv_file):
    # first element in the line is assumed to be the key ("eggs", "bacon", etc.)
    key = line[0]
    # update the data values for this key
    summary[key][0].append(lineno)
    summary[key][1].append(something_else)
    # ... etc.

I find this kind of indexed access a bit fragile though, and prefer keyed or attribute access. Your hardcoded list of 4 lists may be better represented as a dict or even objects of some simple data-tallying class.

Also, I think your "eggs", "bacon", and "ham" list will grow over time, as you find entries in your CSV file for "pancakes", "waffles", "hash browns" and so on. I have gotten to use defaultdict's more and more lately for tallying up data as I go through data files or database tables. Instead of pre-defining what keys I expect to get (and having to update the list myself when the input data gets new values added to it), defaultdict just adds new entries of the form I define:

class Tally(object):
    def __init__(self):
        self.count = 0
        self.lines = []
        self.values = []

from collections import defaultdict
summary = defaultdict(Tally)

for lineno,line in enumerate(csv_file):
    # first element in the line is assumed to be the key ("eggs", "bacon", etc.)
    key = line[0]
    # update the data values for this key
    summary[key].count += 1
    summary[key].lines.append(lineno)
    summary[key].values.append(line[1])
    # ... etc.

defaultdict saves me the cumbersome and repetitive "if key not in summarydict: add new entry..." overhead, so my code stays fairly clean.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文