简体   繁体   中英

Searching through list of lists

I'm pretty new to python, and I'm stuck on a loop/list problem. I have two lists and want to search through the lists to find matching elements and add an item from that list to a new list.

Here's my code:

newList = []
elements = [["Wood", "elem1"], ["Stone", "elem2"], ["Concrete", "elem3"]]
nameNum = [["Wood", "2316"], ["Concrete", "3360"], ["Stone", "2785"]]

The lists can be longer and not always the same length, but just using 3 examples. What I actually need is newList = ["2316", "2785", "3360"] .

from what I understand you want to build a new list from list2 nested elements if the first element from the inner lists is in the list1 in one of the nested lists on the first position:

list1 = [["a", 1], ["b", 2], ["c", 3]]
list2 = [["a", 1], ["c", 3], ["b", 2]]

added = {e[0] for e in list1}

new_list = [e[1] for e in list2 if e[0] in added]

print(new_list)

output:

[1, 3, 2]

after your edit

you can use:

d = {e[0]: i for i, e in enumerate(elements)}
p = sorted([e for e in  nameNum if e[0] in d], key= lambda x: d[x[0]])
newList = [s for _, s in p]
print(newList)

output:

['2316', '2785', '3360']
elements = [["Wood", "elem1"], ["Stone", "elem2"], ["Concrete", "elem3"]]
nameNum = [["Wood", "2316"], ["Concrete", "3360"], ["Stone", "2785"]]
new_list =[]
for element in elements:
  for num in nameNum:
    if num[0] in element:
      new_list.append(num[1])
      break
print(new_list)

Looping 2 times in an nested list to extract first the element from elements , then second loop to extract value from nameNum

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