python中的条件对列表项

2024-04-20 11:36:13 发布

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

我有这样一个清单:

[u'1.9', u'comment', u'1.11', u'1.5', u'another comment']

我想将它拆分为元组,这样数字字符串(对于isdigit(item[0])True)与紧跟其后的注释配对,或者如果没有注释,则与空字符串配对(即,下一项是另一个数字字符串)。你知道吗

换句话说:

[
  (u'1.9', u'comment'),
  (u'1.11', ''),
  (u'1.5', u'another comment'),
]

最干净的方法是什么,尤其是在列表长度可能是奇数或偶数的情况下?你知道吗


Tags: 方法字符串true列表anothercomment情况数字
3条回答

下面是如何在一个单一的列表理解。你知道吗

my_list = [u'1.9', u'comment', u'1.11', u'1.5', u'another comment']

result = [(x,('' if i + 1 >= len(my_list) or my_list[i + 1].replace('.','').isdigit() else my_list[i + 1])) for i, x in enumerate(my_list) if x and x.replace('.','').isdigit()]

首先,“isdigit”看起来只能是测试整数,所以为了简单起见,我首先假设输入是:

>>> lst = [u'9', u'comment', u'11', u'1001', u'another comment']

那么解决方案是一个线性:

>>> [(i, '') if s.isdigit() else (i, s) for i, s in zip(lst[:-1], lst[1:]) if i.isdigit()]
[(u'9', u'comment'), (u'11', ''), (u'1001', u'another comment')]

解释

zip生成所有对

>>> lst = ['a', 'b', 'c', 'd'] 
>>> zip(lst[:-1], lst[1:]
[('a', 'b'), ('b', 'c'), ('c', 'd')]

然后使用下面的if语句过滤以整数字符串开头的对。你知道吗

>>> [(i, s) for i, s in zip(...) if i.isdigit()]

最后,使用if else语句生成结果,结果可以是(i,'')或(i,s)

顺便说一句,当lst中只有一个元素时,这不起作用。在这种情况下,你应该特别处理。你知道吗

最好使用生成器函数进行配对:

def number_paired(items):
    items = iter(items)
    number = next(items)
    while number is not None:
        comment = next(items, None)
        if comment is None or comment[0].isdigit():
            # really a number, or end of the iterable
            yield number, u''
            number = comment
            continue
        yield number, comment
        number = next(items)

然后,您可以在生成器上迭代,或使用以下命令从中生成一个列表:

result = list(number_paired(items))

这也适用于结尾有数字但没有以下注释的情况:

>>> def number_paired(items):
...     items = iter(items)
...     number = next(items)
...     while number is not None:
...         comment = next(items, None)
...         if comment is None or comment[0].isdigit():
...             # really a number, or end of the iterable
...             yield number, u''
...             number = comment
...             continue
...         yield number, comment
...         number = next(items)
... 
>>> items = [u'1.9', u'comment', u'1.11', u'1.5', u'another comment']
>>> list(number_paired(items))
[(u'1.9', u'comment'), (u'1.11', u''), (u'1.5', u'another comment')]
>>> list(number_paired(items + [u'42']))
[(u'1.9', u'comment'), (u'1.11', u''), (u'1.5', u'another comment'), (u'42', u'')]

相关问题 更多 >