简体   繁体   中英

How do I efficiently extract all elements in a column from a dictionary whose values are 2D lists in Python?

I have a dictionary whose values are lists of lists.

mydict = {
"A" : [["gactacgat", "IE"],["gactacgat", "IE"]],
"G" : [["ggctacgat", "EI"],["gactacgat", "IE"]],
"C" : [["gcctacgat", "N"],["gactacgat", "IE"]],
"T" : [["gtctacgat", "IE"],["gactacgat", "IE"]]
}

And I am trying to create a list containing all of the elements in the second column of these 2D lists. This is what I am doing:

  mylist = []
  for key in mydict.keys():
      for row in mydict[key]:
          mylist.append(row[1])

Is there a more efficient way of accessing a specific index from all the lists in these lists of lists than what I have done?

(I apologize if my wording was bad, and any feedback for a better title question is appreciated)

List comprehensions are your friend:

mylist = [row[1] for value in mydict.values() for row in value]

This uses a nested loop, but presumably a bit better optimized. Additionally, using dict.values saves you a key lookup at each iteration of the outer loop, and returns items in the same order as the keys would be.

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