最簡單的一種是使用列表理解:
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']
你是如何結束這個名單? **你嘗試了什麼**? –
@MarkusUnterwaditzer我從python中的postgres表中提取了一列。 – shreyj