简体   繁体   English

如何将多个元组中的第一个元素作为字典中的键返回

[英]how to return first element in multiple tuples as keys in dictionary

For example, if 例如,如果

a = {('a','b','c'):2, ('b','c','d'):3}

I want to return only 'a','b' . 我想只返回'a','b'

I tried: 我试过了:

for key in a:

    return key[0]

but it only returned 'a' . 但它只返回'a'

Is there a proper way of finding first element without using lambda or counter or stuff like that (this is a basic course in python). 是否有一种正确的方法来查找第一个元素而不使用lambda或counter或类似的东西(这是python中的基本课程)。 So, no other input program. 所以,没有其他输入程序。

The function (and therefore your for loop) ends as soon as it hits return . 函数(以及你的for循环)在return立即结束。 You should store the values in a list and then return that. 您应该将值存储在列表中,然后返回该值。 Something like: 就像是:

def getFirstElems(dic):
    firstElems = []
    for key in dic:
        firstElems.append(key[0])
    return firstElems

Then if you run that function like this: 然后,如果你像这样运行该函数:

a = {('a','b','c'):2, ('b','c','d'):3}
elem1, elem2 = getFirstElems(a)
print "elem1:", elem1
print "elem2:", elem2

You get this output: 你得到这个输出:

elem1: a
elem2: b

do you want something like this 你想要这样的东西吗?

In [4]: a = {('a','b','c'):2, ('b','c','d'):3}

In [5]: [key[0] for key in a.keys()]
Out[5]: ['a', 'b']

The problem with your code is the return statement... you should hold all the results before returning... 您的代码的问题是return语句...您应该在返回之前保留所有结果...

if you want individual elements every time you can use generators 如果你每次都可以使用generators你想要个别元素

In [19]: def mygenerator():
   ....:     a = {('a','b','c'):2, ('b','c','d'):3}
   ....:     for k in a.keys():
   ....:         yield k[0]
   ....:

In [20]: mg = mygenerator()

In [21]: print(mg)
<generator object mygenerator at 0x035FA148>

In [22]: for i in mg:
   ....:     print i
   ....:
a
b

from what i can tell you want to loop over the keys of the dict. 从我可以告诉你想要循环键盘的键。 try 尝试

for k in a.keys():

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

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