1

For example

a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

And I want to get a matrix c:

c = [0.5, 0.8, 0, 0.11, 0, 0]

That's like if the i in a = ww for ww,ee in n for n in b, then replace with ee else 0

I try some if and else command and here is my code

for n in b:
for t,y in n:
    for tt in a:
        mmm = [y if t == ''.join(tt) else ''.join(tt)]
        print(mmm)

But it failed. How should I code for this situation?

Austin
  • 25,759
  • 4
  • 25
  • 48
wayne64001
  • 399
  • 1
  • 3
  • 13

3 Answers3

1

chain + dict + list comprehension

Your b mapping is a list of lists, you can flatten this into an iterable of tuples via chain.from_iterable. Then feed to dict to create an efficient mapping.

Finally, use a list comprehension with dict.get for the desired result. Just remember to convert the values of a from str to int.

from itertools import chain

a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

b_dict = dict(chain.from_iterable(b))
c = [b_dict.get(i, 0) for i in map(int, a)]

print(c)

[0.5, 0.8, 0, 0.11, 0, 0.23]
jpp
  • 159,742
  • 34
  • 281
  • 339
0

This iterates through list a comparing it's value with first value of tuples in b list. This appends the second value of tuple to output list if the first value of tuple matches with the value in a:

from itertools import chain

a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

b = list(chain.from_iterable(b))
lst = []
for x in a:
    for y, z in b:
        if y == int(x):
            lst.append(z)
            break
    else:
        lst.append(0)

print(lst)
# [0.5, 0.8, 0, 0.11, 0, 0.23]
Austin
  • 25,759
  • 4
  • 25
  • 48
0

You can convert your double-list of mappings into a lookup dictionary and use a list-comp:

a = ['1', '2', '3', '4', '5', '6']
b = [[(1, 0.5), (2, 0.8)], [(4, 0.11), (6, 0.23)]]

# convert b to a dictionary:
d = {str(k):v for tup in b for k,v in tup} # stringify the lookup key value 
print(d)

# apply the lookup to a's values
result = [d.get(k,0) for k in a]
print(result)

Output:

# the lookup-dictionary
{'1': 0.5, '2': 0.8, '4': 0.11, '6': 0.23}

# result of list c,omprehension
[0.5, 0.8, 0, 0.11, 0, 0.23]

Related:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69