简体   繁体   English

在字典Python中访问元组中的元素

[英]Accessing an element in tuple in a dictionary Python

I'm writing a code to identify the subfix for a given number. 我正在编写代码以标识给定数字的子修补程序。 I have a bunch of if statements to figure out the subfix. 我有一堆if语句来找出子修补程序。 However I thought that a more elegant solution would be a dictionary. 但是我认为一个更优雅的解决方案是字典。 So I have the below dictionary: 所以我有以下字典:

The issue is, if I write 9 in subfix , the result is False. 问题是,如果我9 in subfix写入9 in subfix ,则结果为False。 How do I access the elements in the tuple in the dictionary? 如何访问字典中元组中的元素?

 subfix = {(0, 4, 5, 6, 7, 8, 9, 11, 12, 13): 'th', 1: 'st', 2: 'nd', 3: 'rd'}

For example, I would like to write something simple like: 例如,我想写一些简单的东西:

def subf(a):
     if a in subfix:
           ending = subfix.get(a)
     print('We met on the ',a,ending,'.'sep='')

which would print 'We met on the 1st.' 上面会显示“我们在1日见过面”。 (but doesn't work for 0,4,5,6,7,8,9,11,12,13) How do I get it to work for those elements? (但不适用于0、4、5、6、7、8、9、11、12、13)如何使它们适用于那些元素?

Because of its internal implementation as a hash table, a dictionary maps single keys to single values. 由于其内部实现为哈希表,因此字典将单个键映射到单个值。 While you could dynamically construct a dictionary that has the format you need, I think a good alternative way to think about this problem is the following: 虽然您可以动态构造具有所需格式的字典,但我认为考虑此问题的一种不错的替代方法如下:

  • For the special cases 1 , 2 and 3 , we use the special values from a dictionary 对于特殊情况123 ,我们用特殊值从字典
  • For all other cases, we use th as a suffix. 对于所有其他情况,我们使用th作为后缀。

Luckily the default parameter of dict.get() comes to the rescue here: 幸运的是, dict.get()default参数在这里可以解决:

subfix = {1: 'st', 2: 'nd', 3: 'rd'}
def subf(a):
    ending = subfix.get(a, 'th')
    print('We met on the {}{}.'.format(a, ending))

This will use the value from the dict if it has the key, otherwise it will use th . 如果它具有键,它将使用dict中的值,否则将使用th

EDIT : As for how to construct a dictionary that has the necessary format, we could use: 编辑 :至于如何构造具有必要格式的字典,我们可以使用:

subfix = { 1: 'st', 2: 'nd', 3: 'rd'}
for k in (0, 4, 5, 6, 7, 8, 9, 11, 12, 13):
    subfix[k] = 'th'

Note that I just included this for completeness' sake, I don't consider this elegant. 请注意,出于完整性考虑,我只是将其包括在内,我认为它并不优雅。

You need to know what the operations you're using actually do. 您需要知道您实际使用的操作是什么。 something in some_dictionary isn't whatever arbitrarily defined notion of "in" test you happen to want at the time. something in some_dictionary内容并不是您当时偶然想要的“在”测试中任意定义的概念。 It tests whether something is a key of some_dictionary . 它测试something是否是some_dictionary的键。 9 is not a key of subfix , so 9 in subfix rightly returns False . 9 不是 subfix的键,因此subfix 9正确返回False

Take a step back and think about subfix What does it do? 退后一步,考虑一下subfix作用是什么? What is it for? 这是为了什么 In a definition like this: 在这样的定义中:

subfix = {1: 'st', 2: 'nd', 3: 'rd'}

I would say that subfix represents a mapping from numbers to the suffix used for the ordinal version of each number. 我要说的是,该subfix代表从数字到用于每个数字的序数版本的后缀的映射。 OTOH this definition: OTOH这个定义:

subfix = {(0, 4, 5, 6, 7, 8, 9, 11, 12, 13): 'th', 1: 'st', 2: 'nd', 3: 'rd'}

represents something like "a mapping from tuples of numbers that share a common ordinal suffix OR single numbers to their ordinal suffix". 表示类似“从具有共同序数后缀或单个数字的元组到其序数后缀的映射”。 What this definition represents is much more complex, and so using it is much more complex. 此定义表示的内容复杂得多 ,因此使用它要复杂得多。 If you have an arbitrary number and you want to find its ordinal suffix, you need to find out whether it is a key in the dictionary or whether it is an element of any of the keys of the dictionary. 如果您有一个任意数字,并且要查找其序数后缀,则需要找出它是字典中的键还是字典中任何键的元素。 This means the dictionary doesn't allow you to jump straight to the ordinal suffix from the number, nor does it allow you to quickly check whether any number is in the mapping. 这意味着字典不允许您直接从数字跳到序数后缀,也不允许您快速检查映射中是否有任何数字。 So I think it's the wrong data structure to use in this case; 因此,我认为在这种情况下使用错误的数据结构; a direct mapping from numbers to suffixes would be much easier to use. 从数字到后缀的直接映射会更容易使用。

You need to use the numbers individually as keys. 您需要单独使用数字作为键。 You can create the dict manually, or do something like this: I'm not sure which is better: 您可以手动创建字典,也可以执行以下操作:我不确定哪个更好:

suffixes_list = [
    ((0, 4, 5, 6, 7, 8, 9, 11, 12, 13), "th"),
    ((1,), "st"),
    ((2,), "nd"),
    ((3,), "rd"),
]

suffixes = {}
for nums, suffix in suffixes_list:
    for num in nums:
        suffix[num] = suffix

The simplest: 最简单的:

 subfix = {1: 'st', 2: 'nd', 3: 'rd'}
 subfix.get(num, 'th')

The get command will return st for 1, nd for 2, rd for 3 and th for anything else. get命令将返回st为1,nd为2,rd为3,th为其他值。

Another alternative is to use a tuple, you don't really need a dictionary here. 另一种选择是使用元组,这里您实际上不需要字典。

subfix = ('','st','nd','rd','th','th','th','th','th','th',)

To unpack your multiple-key dictionary into a dictionary mapping single keys to values: 要将多键字典解压缩为将单个键映射到值的字典,请执行以下操作:

subfix = subfix((key, value) for key in keys if isinstance(keys, tuple) else (keys,) 
                for keys in subfix.items())

Note that this isn't implying that your original data structure was a good idea (as Ben said, it has a confused type) but it's as well to know how to do this, in particular how to use nested generator (or list) comprehensions. 请注意,这并不意味着您原始的数据结构是一个好主意(正如Ben所说,它具有混淆的类型),但是也知道如何执行此操作,尤其是如何使用嵌套的生成器(或列表)理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM