0

I am new to python, and am setting up a large dataset to work on, and wanted to check and make sure that I am doing this in the most optimized manner possible, which right now I am pretty sure I am not. I have a python dictionary that is currently set up as so.

list1 = [1,2],[3,4],[4,5]
list2 = [10,20],[30,40],[50,60]
list3 = [100,200],[300,400],[400,500]

These list are created programmatically (and much larger in reality), and are then sorted into a dictionary as follows:

l_dict = {"l1":list1,"l2":list2,"l3":list3} 
print l_dict  
    `{'l2': ([10, 20], [30, 40], [50, 60]), 'l3': ([100, 200], [300, 400], [400, 500]), 'l1': ([1, 2], [3, 4], [4, 5])}`

I have another dicitonary set up exactly the same, except with different numbers and object name (call it k_dict). Here are my questions: What is the simplest way to get an array/list of the first object in each tupple? My code now is as follows:

#Gets first tuple value from each list 
listnames = ["l1","l2","l3"]
i=10
while(i < len(listdict)):
 for x,a in l_dict[listnames[i]]:
  return a[0]
 i+=1

Which was working

Should return something like (1,3,4,10,30,50,100,300,400) except spaced with newlines

I have also tried dict comprehension

print {x[0] for x in ldict[listnames]}

Which never worked for me, and I have tried many similar variations that wouldn't work either.

Also, is this dictionary a good way to set this data up? I couldn't find any other examples of list of tuples inside dictionaries, which leads me to believe there might be some dataframe/other manner of storing data like this that is easier to use. I am using python 2.7.1

4

3 回答 3

1

Use this list comprehension:

In [16]: [y[0]  for x in listnames for y in l_dict[x]]
Out[16]: [1, 3, 4, 10, 30, 50, 100, 300, 400]

Above list comprehension is equivalent to:

In [26]: lis=[]

In [27]: for x in listnames:
   ....:     for y in l_dict[x]:
   ....:         lis.append(y[0])
   ....:         

In [28]: lis
Out[28]: [1, 3, 4, 10, 30, 50, 100, 300, 400]
于 2013-04-08T23:07:03.303 回答
0

听起来您正在寻找经常想要的zip。看这个:

list1 = [1,2],[3,4],[4,5]
print zip(*list1)
# [(1, 3, 4), (2, 4, 5)]

如果您真的只想使用第一对

from itertools import izip
generator = izip(*list1)
first = next(generator)
于 2013-04-08T23:09:32.790 回答
0

假设 k_dict 和 l_dict 具有相同的结构,您可以通过迭代它们来比较它们的值,如下所示:

for listname in listnames:
   for i, lv in enumerate(l_dict[listname]):
      kv = k_dict[listname][i]
      #lv and kv will contain a pair of values, e.g [1,2] or [200,300]
      if lv[0] == kv[0]:
          #do something
          pass

但是,因为您的字典值是元组,所以它们是不可变的。您可能希望将它们改为列表,以便您可以更改它们的值,例如:

l_dict = {k:list(v) for k,v in l_dict.iteritems()}
于 2013-04-08T23:21:05.107 回答