To do a double list flatten

Asked 1 years ago, Updated 1 years ago, 115 views

['[ abc, def ]', '[ ghi, abc ]', '[ def ]']

I'd like to change the above double list to a one-dimensional list.

That is,

['abc', 'def', 'ghi']

I want to convert it as above.

Converting using itertools

['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i']

It's all split up like this TT

Is there a way?

python nlp list

2022-09-21 13:52

1 Answers

First, ['[abc, def]', '[ghi, abc]', and '[def]' are not a double list, but a list of strings.

I think they wanted the results under the following conditions.

L = [['abc', 'def'], ['ghi', 'abc'], ['def']]

import itertools as it 

set(it.chain(*L))                                                      
{'abc', 'def', 'ghi'}

If the conditions were ['[abc, def]', '[ghi, abc]', '[def]']', you should make a double list using regular expressions, etc.

import re

L = ['[ abc, def ]', '[ ghi, abc ]', '[ def ]']
L2 = [re.findall(r'(\w+)[,]?', s) for s in L]

import itertools as it 

set(it.chain(*L2))


2022-09-21 13:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.