简体   繁体   English

如何从值是python2.7中列表列表的字典中选择?

[英]How do I select from a dictionary whose values are a list of lists in python2.7?

I have a dictionary with key value pairs, as they are. 我有一本包含键值对的字典。 The values are all lists or lists of lists. 值是所有列表或列表列表。

For a dictionary that looks like this: 对于这样的字典:

    d={}
    d['FM_001323'] = [[45,11232],[300,400],[65,700]]
    d['FM_094326'] = [11500,12500]

If I want to see the first entry for each list in the value by each key, I can't just do the below like I could if every entry was a list of lists: 如果要通过每个键查看值中每个列表的第一个条目,则不能像每个条目都是列表的列表那样进行以下操作:

    for j in d:
           for i in range(0,len(d[j]):
                  print d[j][i][0]

Because the second key in my dictionary only has a single list for a value, not a list of lists, and the [0] index doesn't have any reference. 因为字典中的第二个键只有一个值列表,而不是列表列表,并且[0]索引没有任何引用。 Does that make sense? 那有意义吗?

I want to isolate the first entry in each list-value for each key. 我想隔离每个键的每个列表值中的第一个条目。 It's easy with either list-values or lists of list-values, but mixing them together complicates it. 使用列表值或列表值列表很容易,但是将它们混合在一起会使它变得复杂。

I am also open to easier ways to reach the same goal. 我也乐于寻求更简单的方法来实现相同的目标。 For context: I am trying to compare the numbers in the values with variables from other parts of this code by that FM_ figure. 对于上下文:我试图通过FM_数字将值中的数字与该代码其他部分的变量进行比较。 Any way of isolating these would suffice for me. 隔离这些的任何方法对我来说就足够了。

Expected output would be 预期输出为

    45
    300
    65
    11500

One way of doing is "Asked Forgiveness Not Permission" 一种方法是"Asked Forgiveness Not Permission"

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]

for j in d:
    for i in range(0,len(d[j])):
        try:
            print(d[j][i][0])
        except TypeError:
            print(d[j][0])
            break

prints: 印刷品:

45
300
65
11500

Basically just do it in try blocks and catch the exception that will throw if it didn't work out and try it again with something else. 基本上,只需在try块中执行此操作,然后捕获如果无法解决的异常将引发的异常,然后再尝试其他操作。

Edited so to OP's desired output. 编辑为OP所需的输出。 Just break out of the loop after the first print because your second for loop is there to loop through the sub lists right? 只需在第一次打印后跳出循环,因为您的第二个for循环就可以循环浏览子列表了吗? You don't have a sub list so just break out of it 您没有子列表,所以就打破它吧

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]
for k in d:
    for v in d[k]:
        if isinstance(v, list): 
            print v[0]    
        else:
            print v

Output: 45 300 65 11500 12500 输出:45300 65 11500 12500

Or cleaner and shorter: 或更清洁或更短:

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]

for j in d.itervalues():
    for i in j:
        if isinstance(i,list):
            print(i[0])
        else:
            print(i)

Only a single additional line is required in your code. 您的代码中仅需添加一行。 You should have a check on the element type. 您应该检查元素类型。 Something like this: 像这样:

for j in d:
    for i in range(0,len(d[j])):
        #See the line below.
        if type(d[j][i]) == type([]):
           print(d[j][i][0])
        else
            print(d[j][i])

Note: in case you want to print only the first element when the d[j] only have numbers and no lists. 注意:如果d [j]仅具有数字且没有列表,则只想打印第一个元素。 you may have to run an additional loop to find out whether d[j] has any list in it or not. 您可能必须运行一个附加循环才能找出d [j]中是否有任何列表。 See code below: 参见下面的代码:

for j in d:
    #Check if all elements in d[j] are int.
    for i in d[j]:
        if type(i) ==type([]):
            break
    else:
        print(d[j][0])
        continue

    for i in range(0,len(d[j])):
        #See the line below.
        if type(d[j][i]) == type([]):
           print(d[j][i][0])
        else:
            print(d[j][i])

So for d[j] = [11500,[1,2],1300] , 11500 1 and 1300 would be printed. 因此,对于d [j] = [11500,[1,2],1300] ,将打印11500 11300

Another way would be to convert to str first and march on r'\\[{0-9}+' , which would give all leading elements: 另一种方法是先转换为str然后在r'\\[{0-9}+' ,这将给出所有前导元素:

from __future__ import print_function
import re

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]

for v in d.values():
    print('\n'.join(s[1:] for s in re.findall(r'\[[0-9]+', str(v))))

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

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