Working with python lists

5

I have the following list

lista=[('1', '3', 0.29), ('1', '2', 0.36), ('1', '5', 0.32),
       ('1', '7', 0.19), ('0', '2', 0.26), ('0', '4', 0.38),
       ('0', '7', 0.16), ('0', '6', 0.58), ('3', '2', 0.17),
       ('3', '6', 0.52), ('2', '7', 0.34), ('2', '6', 0.4),
       ('5', '4', 0.35), ('5', '7', 0.28), ('4', '7', 0.37),
       ('4', '6', 0.93)]

I need to find a way for sublists that have '1' 'to give me the values of the other whole number in the list. that is to say I must get the data '3', '2', '5', '7'

thanks

    
asked by helperino 18.06.2017 в 01:50
source

2 answers

12

You do not specify it, but if the integer to return is always in the second position with a simple for to get each tuple and a conditional to see if the first element is '1' is enough. Using compression of lists:

lista=[('1', '3', 0.29), ('1', '2', 0.36), ('1', '5', 0.32),
       ('1', '7', 0.19), ('0', '2', 0.26), ('0', '4', 0.38),
       ('0', '7', 0.16), ('0', '6', 0.58), ('3', '2', 0.17),
       ('3', '6', 0.52), ('2', '7', 0.34), ('2', '6', 0.4),
       ('5', '4', 0.35), ('5', '7', 0.28), ('4', '7', 0.37),
       ('4', '6', 0.93)]

res = [tupla[1] for tupla in lista if tupla[0] == '1']
print(res)

Lists / iterators / sets by compression are more efficient, anyway if you do not feel like with them, the above is equivalent to:

res = []
for tupla in lista:
    if tupla[0] == '1':
        res.append(tupla[1])
print(res)

With this you get a list as output, the idea is the same if you want to get an iterator, a set or simply print the output without storing it.

Exit:

  

['3', '2', '5', '7']

    
answered by 18.06.2017 в 01:55
2

Simply because yes ... the same but "functional"

result = map(lambda x: x[1], filter(lambda x: x[0] == '1', lista))

If you're in Python 3, that returns a "generator", so if you need a list

result = list(map(lambda x: x[1], filter(lambda x: x[0] == '1', lista)))
    
answered by 20.06.2017 в 13:47