Find values ​​in a shuffled list of subscriptions by one of the values

I have a list if lists

items = [
    ["e",None,None],
    ["pork","pork.png","meat"],
    ["beef","b.png","meat"],
    ["cheese","c.png","not"],
    ]
items_list = ["e","beef","pork","beef"]
shuffle(items_list)

      

how can I print the second or third value in the sublists without their index?

for i in items_list:
    print ???

      

+3


source to share


2 answers


You can store the signatures items

in a dictionary indexed by their first elements.

from random import shuffle

items = [
    ["e",None,None],
    ["pork","pork.png","meat"],
    ["beef","b.png","meat"],
    ["cheese","c.png","not"],
]

items_dict = {u[0]: u for u in items}

items_list = ["e","beef","pork","beef"]
shuffle(items_list)

for s in items_list:
    print(s, items_dict[s])

      

Output

beef ['beef', 'b.png', 'meat']
e ['e', None, None]
beef ['beef', 'b.png', 'meat']
pork ['pork', 'pork.png', 'meat']

      




To print the second element (e.g. PNG):

for s in items_list:
    print(s, items_dict[s][1])

      

Output

e None
beef b.png
beef b.png
pork pork.png

      




This is quite efficient because the new lists are not executed: the lists in items_dict

are the same list objects that are in items

. Therefore, if you want, you can mutate these lists either through items

or items_dict

.

items_dict["cheese"].append("cheddar")
print(items[3])

items[0][2] = "something"
print(items_dict["e"])

      

Output

['cheese', 'c.png', 'not', 'cheddar']
['e', None, 'something']

      




You don't need items_dict

, but the alternative is a double loop for

, which becomes very inefficient if items

large.

for s in items_list:
    for seq in items:
        if seq[0] == s:
            print(s, seq)
            break

      

Output

beef ['beef', 'b.png', 'meat']
e ['e', None, None]
beef ['beef', 'b.png', 'meat']
pork ['pork', 'pork.png', 'meat']

      

0


source


How about this:

from random import shuffle

items = [
    ["e",None,None],
    ["pork","pork.png","meat"],
    ["beef","b.png","meat"],
    ["cheese","c.png","not"],
    ]

items_list = ["e","beef","pork","beef"]
shuffle(items_list)

for item in items_list:
    for orig_item in items:
        try:
            orig_item.index(item)
            print(item, orig_item)
        except ValueError:
            pass

      

Output:



beef ['beef', 'b.png', 'meat']
pork ['pork', 'pork.png', 'meat']
e ['e', None, None]
beef ['beef', 'b.png', 'meat']

      

It might be slower than @ PM 2Ring's answer (I haven't measured) due to two loops and exception handling.

use orig_item[1]

to access the second item of the sublist

0


source







All Articles