Python将列表列表转换为元组列表
我正在尝试将列表列表转换为元组列表 我的Python 2.6.8代码是:Python将列表列表转换为元组列表,python,list,casting,tuples,Python,List,Casting,Tuples,我正在尝试将列表列表转换为元组列表 我的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_s
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
行5
和8
不会将我的列表转换为元组,有没有办法将f
s和b
s转换为元组
回答-在评论中:
我们需要做d['bar']=map(tuple,d['bar'])
好的,那么:
d['foo'] = map(tuple, d['foo'])
d['bar'] = # etc...
如果您想使2.x和3.x都能使用此功能,请改用列表comp:
d['foo'] = [tuple(el) for el in d['foo']]
然后可能会让它更通用一些:
for key in ('foo', 'bar'):
d[key] = [tuple(el) for el in d[key])
d['bar']=map(tuple,d['bar'])
很可能就是你想要的——它完美地解决了!