2013-12-07 241 views
0

我試圖將列表列表轉換爲元組列表。Python將列表列表轉換爲元組列表

我的Python 2.6.8的代碼是:

1. dicts = List of dictionaries all with same set of keys foo and bar 
2. for d in dicts: 
3.  for f in d['foo']: # d['foo'] is a list of lists 
4.   f.change_some_stuff_inplace(with_some_other_stuff) 
5.   f = tuple(f) # this obviously doesn't work - it just converts f locally 
6.  for b in d['bar']: # d['bar'] is also a list of lists 
7.   b.change_some_stuff_inplace(with_yet_some_other_stuff) 
8.   b = tuple(b) # again this doesn't work 

線條58不投我的名單到元組,是有辦法的f S和b秒值進行轉換,以就地元組?

ANSWER - 在註釋:

需要做的d['bar'] = map(tuple, d['bar'])

+1

'd [ '酒吧'] =地圖(元組,d [ '酒吧'])'可能是你 –

+0

後在做什麼,我 - 它的工作完美! – baibo

回答

2

那麼好吧:

d['foo'] = map(tuple, d['foo']) 
d['bar'] = # etc... 

如果你想使這個工作既2.x和3.x,然後用列表比較,而不是:

d['foo'] = [tuple(el) for el in d['foo']] 

然後可能使多一點通用:

for key in ('foo', 'bar'): 
    d[key] = [tuple(el) for el in d[key])