简体   繁体   中英

python nested list retrieve and print specific elements

I have a nested list that looks like this. It is supposed to represent people and their possible connections. I need to output the number in quotes along with connections they might know (numbers in the sublist with 2 or 3 after the colon along with a list of people they probably (numbers in the sublist with 4 or more after the colon),so it looks like this:

6:Might(1,3,4,7,11)
1:Might(4,6,7) Probably(11)
4:Might(1,3,6,11,12) 

here is my nested list

    connect_cnt =   [(6, {3: 3, 4: 3, 7: 2, 13: 1, 1: 3, 11: 2, 12: 1}),  
       (1, {7: 3, 5: 1, 9: 2, 11: 4, 10: 1 , 2: 1, 13: 1, 3: 2, 6: 3, 4: 3, 12: 2}),                                     
       (4, {3: 2, 7: 3, 6: 3, 13: 1, 1: 3, 11: 2,12: 3, 5: 1, 2: 1, 9: 1}), 

I am not sure how to go about it. I tried this for starters just to see if I could get the count but it didn't work.

     final_dict 
     for row in range(len(connect_cnt)):
        for col in  range(len(connect_cnt[row])):
           key,value = connect_cnt[row].split(':')
           if value > 1:
               final_dict[key] = value

Even if I cold just get the ones I need to print in a nested list. I am a beginner and don't have much experience with nested lists.

I'm not sure of the exact solution to your answer, but I can provide a generalized solution which you can adapt to your needs.

l = [(1, {2: 3, 4: 5}), (6, {7: 8, 9: 10})]
# to change a value
l[0][1][2] = 100 # now l = [(1, {2: 100, 4: 5}), (6, {7: 8, 9: 10})] 

If this does not work for your example, please provide more information, and I will try my best to help out.

Edit: This code should extract all key-value pairs to another dictionary, given that a dictionary are always the second element of the sub-list.

final_dict = {}
for i in l:
    for j in i[1].keys():
        final_dict[j] = i[j]

Edit 2: I think I understand now. This code should do it:

for i in l:
    for j in i[1].keys():
        if i[1][j] <= 1:
            del i[1][j]

Edit 3: Sorry. Let me know if this works:

l2 = []
for i in l:
    d = {}
    for j in i[1].keys():
        if i[1][j] > 1:
           d[j] = i[1][j]
    l2.append((i[0], d))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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