2

I'm looking for a commande in python in order to only keep within a list the 3 first letters between content_content > con_con here is an example:

list_exp=["Babylona_expetiendra","Ocracylus_machabrus","Ojeris_multifasciatus"]

list_exp=["Bab_exp","Ocr_mac","Oje_mul"]

Does anyone have an idea? Thank you for your help .

thomas
  • 624
  • 1
  • 12
  • 27
chippycentra
  • 879
  • 1
  • 6
  • 15

3 Answers3

4

You can use a list-comprehension:

['_'.join(map(lambda x: x[:3], x.split('_'))) for x in list_exp]

Code:

list_exp=["Babylona_expetiendra","Ocracylus_machabrus","Ojeris_multifasciatus"]

print(['_'.join(map(lambda x: x[:3], x.split('_'))) for x in list_exp])
# ['Bab_exp', 'Ocr_mac', 'Oje_mul']
Austin
  • 25,759
  • 4
  • 25
  • 48
  • Could you please explain how you came up with this list comprehension! I want to start learning list-comprehension to solve complex problems like these @austin – Devesh Kumar Singh Apr 23 '19 at 09:16
  • @DeveshKumarSingh, comprehension takes each element splits on `'_'` and with `map` gets first three chars out of each split and a final `join` brings the expected output. What you do in normal way is summed up. Nothing fancy. – Austin Apr 23 '19 at 09:27
  • Thank you for your help. – chippycentra Apr 23 '19 at 14:35
1

You can try like this.

Before running all these, just have a quick look at the use of list comprehension & join(), split() methods defined on strings.

>>> list_exp = ["Babylona_expetiendra","Ocracylus_machabrus","Ojeris_multifasciatus"]
>>> 
>>> output = ['_'.join([part[:3] for part in name.split("_")]) for name in list_exp]
>>> output
['Bab_exp', 'Ocr_mac', 'Oje_mul']
>>> 
hygull
  • 8,464
  • 2
  • 43
  • 52
1
[
    *map(
        lambda strip:'_'.join([st[:3] for st in strip]),
        [
            *map(
                lambda s:s.split('_'),
                ["Babylona_expetiendra","Ocracylus_machabrus","Ojeris_multifasciatus"]
            )
        ]
    )
]

mess explanation:

First we are splitting every string in list by '_' gigving us

[['Babylona', 'expetiendra'], ['Ocracylus', 'machabrus'], ['Ojeris', 'multifasciatus']]

Then we are getting first 3 letters using [:3] for every string inside new lists

Finnaly joining again with '_'.join()

['Bab_exp', 'Ocr_mac', 'Oje_mul']

This example using map unpacking and lamdas

EvGEN Levakov
  • 23
  • 1
  • 8