0

可能重复:
将元组列表转换为列表?

我有一个这样的清单

[('Knightriders',), ('The Black Knight',), ('Fly by Knight',), ('An Arabian Knight',), ('A Bold, Bad Knight',)...]

我想将其转换为:

['Knightriders', 'The Black Knight', 'Fly by Knight', 'An Arabian Knight', 'A Bold, Bad Knight',...]

完成此任务最耗时的方法是什么?

4

1 回答 1

10

最简单的一个是使用列表推导:

In [126]: lis=[('Knightriders',), ('The Black Knight',), ('Fly by Knight',), ('An Arabian Knight',), ('A Bold, Bad Knight',)]

In [127]: [x[0] for x in lis]
Out[127]: 
['Knightriders',
 'The Black Knight',
 'Fly by Knight',
 'An Arabian Knight',
 'A Bold, Bad Knight']

或使用itemgetter

In [128]: from operator import itemgetter

In [129]: list(map(itemgetter(0),lis))
Out[129]: 
['Knightriders',
 'The Black Knight',
 'Fly by Knight',
 'An Arabian Knight',
 'A Bold, Bad Knight']

或者:

In [131]: [next(x) for x in map(iter,lis)]
Out[131]: 
['Knightriders',
 'The Black Knight',
 'Fly by Knight',
 'An Arabian Knight',
 'A Bold, Bad Knight']

zip()按照@DSM 的建议使用:

In [132]: zip(*lis)[0]
Out[132]: 
('Knightriders',
 'The Black Knight',
 'Fly by Knight',
 'An Arabian Knight',
 'A Bold, Bad Knight')

或使用ast.literal_eval(最不推荐的解决方案或可能永远不会尝试):

In [148]: from ast import literal_eval

In [149]: literal_eval(repr(lis).replace(",)",")"))
Out[149]: 
['Knightriders',
 'The Black Knight',
 'Fly by Knight',
 'An Arabian Knight',
 'A Bold, Bad Knight']
于 2012-11-11T21:13:35.873 回答