从基于.count Python的列表中删除列表

2024-05-19 01:16:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个列表里有以下列表

results=[['hgd', '2.96', '4,433,389', '-13.7'], ['bbd.a', '2.25', '1,209,421', '-13.1'], ['mri.u', '8.60', '3,000', '-8.5'], ['iam', '1.06', '1,000', '-7.8'], ['hnd', '21.76', '1,180,466', '-7.6'], ['tth', '0.97', '41,777', '-7.6'], ['bbd.b', '1.89', '32,423,597', '-7.4'], ['bbd.pr.c', '15.20', '43,737', '-7.3'], ['esp', '1.96', '87,604', '-7.1'], ['enl', '34.00', '5,239', '-6.2'], ['rmp', '1.83', '2,688,261', '-5.7'], ['amm', '1.39', '63,301', '-5.4'], ['vrx', '41.83', '1,664,689', '-5.4'], ['xtc', '13.45', '63,453', '-5.3'], ['cxr', '36.48', '1,642,197', '-5.0']]

此列表每天更新。有时会有一个列表,其中第一个元素有两个句点(.),如下面的bbd.pr.c

['bbd.pr.c', '15.20', '43,737', '-7.3']

发生这种情况时,我希望删除整个列表。不知道该怎么做。使用count函数

.count('.')<=1

有什么帮助吗


Tags: 列表countprresultsiammriesphnd
2条回答

我从来没有想过filter与列表理解相比是特别可读的,尤其是当您必须使用lambda时。对于这两个Python版本,这里的答案与Smac89的答案相同:

results = [x for x in results if x[0].count('.') <= 1]

x对应于l,但l通常不是一个好名字,因为1lI看起来都太相似了)

对于python 2,使用filter

results=[['hgd', '2.96', '4,433,389', '-13.7'], ['bbd.a', '2.25', '1,209,421', '-13.1'], ['mri.u', '8.60', '3,000', '-8.5'], ['iam', '1.06', '1,000', '-7.8'], ['hnd', '21.76', '1,180,466', '-7.6'], ['tth', '0.97', '41,777', '-7.6'], ['bbd.b', '1.89', '32,423,597', '-7.4'], ['bbd.pr.c', '15.20', '43,737', '-7.3'], ['esp', '1.96', '87,604', '-7.1'], ['enl', '34.00', '5,239', '-6.2'], ['rmp', '1.83', '2,688,261', '-5.7'], ['amm', '1.39', '63,301', '-5.4'], ['vrx', '41.83', '1,664,689', '-5.4'], ['xtc', '13.45', '63,453', '-5.3'], ['cxr', '36.48', '1,642,197', '-5.0']]

results = filter(lambda l: l[0].count('.') <= 1, results)

对于python 3:

results = list(filter(lambda l: l[0].count('.') <= 1, results))

相关问题 更多 >

    热门问题