Concatenate elements of a tuple in a list in python

前端 未结 3 1534
执笔经年
执笔经年 2020-12-09 16:38

I have a list of tuples that has strings in it For instance:

[(\'this\', \'is\', \'a\', \'foo\', \'bar\', \'sentences\')
(\'is\', \'a\', \'foo\', \'bar\', \'         


        
3条回答
  •  借酒劲吻你
    2020-12-09 17:09

    The list comprehension creates temporary strings. Just use ' '.join instead.

    >>> words_list = [('this', 'is', 'a', 'foo', 'bar', 'sentences'),
    ...               ('is', 'a', 'foo', 'bar', 'sentences', 'and'),
    ...               ('a', 'foo', 'bar', 'sentences', 'and', 'i'),
    ...               ('foo', 'bar', 'sentences', 'and', 'i', 'want'),
    ...               ('bar', 'sentences', 'and', 'i', 'want', 'to'),
    ...               ('sentences', 'and', 'i', 'want', 'to', 'ngramize'),
    ...               ('and', 'i', 'want', 'to', 'ngramize', 'it')]
    >>> new_list = []
    >>> for words in words_list:
    ...     new_list.append(' '.join(words)) # <---------------
    ... 
    >>> new_list
    ['this is a foo bar sentences', 
     'is a foo bar sentences and', 
     'a foo bar sentences and i', 
     'foo bar sentences and i want', 
     'bar sentences and i want to', 
     'sentences and i want to ngramize', 
     'and i want to ngramize it']
    

    Above for loop can be expressed as following list comprehension:

    new_list = [' '.join(words) for words in words_list] 
    

提交回复
热议问题