简体   繁体   中英

compare list items in LIST A to each first element in a list of tuples LIST B

My question is almost similar to this one - Comparing a list to aa list of tuples? but i am looking for a solution to just comparing.....

I have

ListA = [2, 1, 1, 1, 1] ListB = [(1, 'Poor'), (2, 'Average'), (3, 'Excellent')] List of tuples.

In the end i want to generate a new List of tuples - LISTC containing all elements in LIST A like this

[(2, 'Average'), (1,'Poor'), ( 1, 'Poor'), (1,'Poor'), (1, 'Poor')]

I have tried this -

first_tuple_elements = [element[0] for element in LISTB]
final_list_of_tuples = ()
for i in LISTA:
    for i in first_tuple_elements:
        final_list_of_tuples = [(i, element[1]) for element in LISTB]

print(final_list_of_tuples)

The above is not giving me what i want, kindly assist

LISTB is a resultset from a database query and LISTA is the computed resultset which i then need to compare with items in LISTB so i can generate

LISTC [(2, 'Average'), (1,'Poor'), ( 1, 'Poor'), (1,'Poor'), (1, 'Poor')]

Convert the ListB to dictionary first:

ListA = [2, 1, 1, 1, 1]
ListB = [(1, 'Poor'), (2, 'Average'), (3, 'Excellent')]

d = dict(ListB)
ListC = [(v, d[v]) for v in ListA]

print(ListC)

Prints:

[(2, 'Average'), (1, 'Poor'), (1, 'Poor'), (1, 'Poor'), (1, 'Poor')]

Try:

ListA = [2, 1, 1, 1, 1]
ListB = [(1, 'Poor'), (2, 'Average'), (3, 'Excellent')]
ListC = []
for i in ListA:
    for j in ListB:
        if i == j[0]:
            ListC.append((i, j[1]))

print(ListC)

output

[(2, 'Average'), (1, 'Poor'), (1, 'Poor'), (1, 'Poor'), (1, 'Poor')]

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