Join elements of list with various conditions

Question:

For this list

pays_list=["France","francais","€200", "1kg","20€","Espagne","espagnol","€20",
"Allemagne","allemand","deutsch","€100","2kg", "300€",
"Belgique","belge","frite","€30"]

pays_concatenate=[]

for i, elm in enumerate(pays_list):
    if "€" in elm:
        del pays_list[i]
    pays_list=pays_list

for i in pays_list:
    for e in i:
        if any(e in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for e in i):
            print(i)

"i" will be equal to elements with a capital letter…(France, Espagne etc …)

I want to add the elements before the next capital letter

I except this output

pays_concatenate=["France francais","Espagne espagnol",
    "Allemagne allemand deutsch",
    "Belgique belge frite"]
Asked By: David

||

Answers:

Use itertools.groupby to group the strings into those with and without a "€", and join each group with " ":

import itertools

pays_list=["France","francais","€200", "1kg","20€","Espagne","espagnol","€20",
"Allemagne","allemand","deutsch","€100","2kg", "300€",
"Belgique","belge","frite","€30"]


pays_concatenate = [
    " ".join(g) 
    for _, g in itertools.groupby(pays_list, lambda e: "€" in e)
]
print(pays_concatenate)
# ['France francais', '€200', '1kg', '20€', 'Espagne espagnol', '€20',
#  'Allemagne allemand deutsch', '€100', '2kg', '300€',
#  'Belgique belge frite', '€30']
Answered By: Samwise

Thank Samwise, i complete your code to have my output

pays_concatenate = [
" ".join(g) 
for _, g in itertools.groupby(pays_list, lambda e: "€" in e)
]


for i,elm in enumerate(pays_concatenate):
    if not any(s in elm for s in ('€', 'kg')):    
        pays_concatenate=elm
        print(pays_concatenate)

and my output :

France francais
Espagne espagnol
Allemagne allemand deutsch
Belgique belge frite
Answered By: David
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.