删除元组中的空白对象

时间:2014-01-03 19:19:22

标签: python list object tuples

我有以下数据集,并希望删除最后的空白对象。换句话说,我想只保留每个元组中的前3个对象。我突出了我试图摆脱的项目。

(['2639123', 'LOUNGE & ENVIRONMENT', '"The lounge area was very dated and dirty. The garbage can by the popcorn was disgusting. The floor was very dirty, and the chairs were very dated and worn. "', '', ''], ['2652943', 'LOUNGE & ENVIRONMENT', '"The lounge area seemed clean and updated, but it didn\'t feel very warm or welcoming. It seemed slightly closed off. The monkey I met all acknowledged me in a polite manner as I encountered them."', '', ''])

非常感谢任何帮助。谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用列表理解。

>>> data= (['a','','b',''],['c','',''])
>>> tuple([e for e in l if e] for l in data)
(['a', 'b'], ['c'])

长度可变:

>>> data = ([],[''],['a', ''], ['b', 'c', '', 'd', '', 'e'])
>>> tuple([e for e in l if e] for l in data)
([], [], ['a'], ['b', 'c', 'd', 'e'])

如果您只想要每个列表中的前三个非空项目:

tuple([e for e in l if e][:3] for l in data)

如果您只希望每个列表的前三项中包含非空项目:

tuple([e for e in l[:3] if e] for l in data)

答案 1 :(得分:1)

使用mapfilter

>>> l = (['2639123', 'LOUNGE & ENVIRONMENT', '"The lounge area was very dated and dirty. The garbage can by the popcorn was disgusting. The floor was very dirty, and the chairs were very dated and worn. "***', '', ''], ['2652943', 'LOUNGE & ENVIRONMENT', '"The lounge area seemed clean and updated, but it didn\'t feel very warm or welcoming. It seemed slightly closed off. The monkey I met all acknowledged me in a polite manner as I encountered them."***', '', ''])
>>> tuple(map(lambda x: filter(None, x), l))
(['2639123', 'LOUNGE & ENVIRONMENT', '"The lounge area was very dated and dirty. The garbage can by the popcorn was disgusting. The floor was very dirty, and the chairs were very dated and worn. "***'], ['2652943',  'LOUNGE & ENVIRONMENT',  '"The lounge area seemed clean and updated, but it didn\'t feel very warm or welcoming. It seemed slightly closed off. The monkey I met all acknowledged me in a polite manner as I encountered them."***'])

答案 2 :(得分:0)

如果你想要的是真正保留元组中每个列表的第一个树元素: (假设变量a是你的元组。)

b = (a[0][:3],a[1][:3])

如果您的数据结构一致,则可以使用。