【问题标题】:Convert list of single element tuples to list of elements [duplicate]将单个元素元组列表转换为元素列表[重复]
【发布时间】:2012-11-11 21:12:32
【问题描述】:

可能重复:
Convert list of tuples to list?

我有一个这样的列表

[('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',...]

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

【问题讨论】:

  • 你是怎么得到这个列表的? 你尝试了什么
  • @MarkusUnterwaditzer 我从 python 中的 postgres 表中提取了一个列。

标签: python


【解决方案1】:

最简单的方法是使用列表推导:

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']

【讨论】:

  • 还有list(zip(*lis)[0])
  • @DSM 哦!我错过了那个。 :)
  • 如果 data 包含列表,则可以执行eval(repr(data).replace('(', '').replace(',)', '')) :-) 之类的操作。不,没有人应该这样做。孩子们,不要在家里这样做!
  • @Matthias literal_eval(repr(lis).replace(",)",")")) 对孩子来说是安全的。 :)
  • 真丢脸!但要让任何想要使用它的人清楚:不要这样做!
猜你喜欢
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多