How to join two strings from different tuples but in the same index using Python?

前端 未结 4 1199
执笔经年
执笔经年 2021-01-22 15:07

The tuples inside the file:

 (\'Wanna\', \'O\')
 (\'be\', \'O\')
 (\'like\', \'O\')
 (\'Alexander\', \'B\')
 (\'Coughan\', \'I\')
 (\'?\', \'O\')
4条回答
  •  难免孤独
    2021-01-22 15:34

    I hadn't seen @MykhayloKopytonenko's solution when I went to write mine, so mine is similar:

    tuples = [('Wanna', 'O'),
              ('be', 'O'),
              ('like', 'O'),
              ('Alexander', 'B'),
              ('Coughan', 'I'),
              ('?', 'O'),
              ('foo', 'B'),
              ('bar', 'I'),
              ('baz', 'B'),]
    results = [(t0[0], t1[0]) for t0, t1 in zip(tuples[:-1], tuples[1:])
                              if t0[1] == 'B' and t1[1] == 'I']
    for r in results:
        print("%s %s" % r)
    

    This outputs:

    Alexander Coughan
    foo bar
    >>> 
    

    If you absolutely must have the result returned as a string, change the list comprehension to:

     results = ["%s %s" % (t0, t1) for t0, t1 in zip(tuples[:-1], tuples[1:])
                                   if t0[1] == 'B' and t1[1] == 'I']
    

    This takes advantage of the fact that, based on your criteria, the last element of your list of tuples will never be returned as the first element of the result set. As a result, the zip effectively steps you through (tuples[n], tuples[n + 1]) so that you can easily examine the values.

提交回复
热议问题