Zeta11
Zeta11

Reputation: 881

Accessing an Element and Its Value in a List

So say I have a list, List1 with lists in it.

list1 = [ [node1, w1], [node2, w2], [node3, w3]]

If node2 is present in list1, I want to get the value of w2. How do I do it in a quick way?

I couldn't find a relevant answer to the question while searching for it in stackoverflow. If there is one, I would be happy to refer to it. Thank you!

Upvotes: 0

Views: 67

Answers (3)

t.m.adam
t.m.adam

Reputation: 15376

Simple :

list1 = [ ['node1', 'w1'], ['node2', 'w2'], ['node3', 'w3'] ]
print([ l[1] for l in list1 if l[0] == 'node2' ][0])

Upvotes: 1

axwr
axwr

Reputation: 2236

getting elements out of lists is relatively simple within python, You just need to index into the list. this can be done to multiple levels ie:

example = [[1,2][2,4]]
print(example[1][1])
# will output 2

However in your specific case you could do:

list1 = [ ["node1", 1], ["node2", 2], ["node3", 3]]
for item in list1:
    if item[0] == "node2":
        print(item[1])

# this will print 2

You could always abstract this into a function and return instead of print for further use.

like this:

list1 = [ ["node1", 1], ["node2", 2], ["node3", 3]]

def ContainedInInnerList(ls, item):
    for x in ls:
        if x[0] == item:
            return(x[1])
    return None

print(ContainedInInnerList(list1, "node2"))
#output: 2

It would also be nice to use more complicated list comprehensions, to read about those go here: http://www.secnetix.de/olli/Python/list_comprehensions.hawk I hope this helped.

Upvotes: 0

JacobIRR
JacobIRR

Reputation: 8946

This is a way of doing what you are asking (using strings instead of your undefined variables):

list1 = [ ['node1', 'w1'], ['node2', 'w2'], ['node3', 'w3']]

for ix, l in enumerate([li for li in list1]):
    if 'node2' in l:
        print list1[ix][1]

If that data structure is not mandatory, a key/value pair structure would be much simpler (and faster! if you have lots of elements) to work with:

d = {'node1': 'w1',
     'node2': 'w2',
     'node3': 'w3'}

print d['node2']
#  prints w2

Upvotes: 1

Related Questions