我有一个像这样的列表
[('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',...]
实现这一目标最耗时的方法是什么?
答案 0 :(得分:9)
最简单的是使用列表理解:
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']
或使用{DSM:
建议的zip()
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']