python - find values in a shuffled list of sublists by one of the values -
i have 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 print second or third value in sublists without index?
for in items_list: print ???
you can store items
sublists in dictionary, indexed 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 u in items} items_list = ["e","beef","pork","beef"] shuffle(items_list) 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 second items (i.e., pngs):
for s in items_list: print(s, items_dict[s][1])
output
e none beef b.png beef b.png pork pork.png
this efficient since no new lists made: lists in items_dict
same list objects in items
. if want, can mutate lists either via 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
, alternative double for
loop, gets very inefficient if items
large.
for s in items_list: 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']
Comments
Post a Comment