Home > Back-end >  Is it possible to use .join() to concatenate a list of strings in a nested list in Python?
Is it possible to use .join() to concatenate a list of strings in a nested list in Python?

Time:09-23

I'm trying to use .join in a nested list with an if statement. If the condition is met, I want to combine all indices from [1:-3]. Every time the .join function doesn't join the index.

Input

list = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e','f','g'], ['a', 'b', 'c', 'd']]

Expected Output

[['a', 'b', 'c', 'd'], ['a', 'b c d', 'e','f','g'], ['a', 'b', 'c', 'd']]

What I have tried:

list = [' '.join(str(inner_list)) for inner_list in list for i in inner_list if len(inner_list) >= 6 ]

I know the for loop is correct because the following code produces true six times.

list = [print("true") for inner_list in list for i in inner_list if len(inner_list) >= 6 ]

CodePudding user response:

for inner_list in list_:
   for i in inner_list:
      if len(inner_list) >= 6:
         print("".join((inner_list)))

output:

a b c d e f g
a b c d e f g
a b c d e f g
a b c d e f g
a b c d e f g
a b c d e f g
a b c d e f g

i converted it to what it actually does , just i did not put it inside a list. if you could specify the output you are looking for. Also in your code you should remove str(inner_list) as i think it is not doing what you intend it to do.

please share intended output too , so i answer better.

your code updated

list = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e','f','g'], ['a', 'b', 'c', 'd']]

list = [' '.join((inner_list)) for inner_list in list for i in inner_list if len(inner_list) >= 6 ]

output list :

['a b c d e f g',
 'a b c d e f g',
 'a b c d e f g',
 'a b c d e f g',
 'a b c d e f g',
 'a b c d e f g',
 'a b c d e f g']

Upon if you want to use that [1:-3] indexing too

list = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e','f','g'], ['a', 'b', 'c', 'd']]

list = [' '.join((inner_list[1:-3])) for inner_list in list for i in inner_list if len(inner_list) >= 6 ]

output list :

['b c d',
 'b c d',
 'b c d',
 'b c d',
 'b c d',
 'b c d',
 'b c d']

ps : also try not to use default keywords as variable names like list

CodePudding user response:

You need to slice the inner lists in the loop, but also pass the remaining inner lists as they are if they're smaller than 6 items. Here's an example:

lst = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['a', 'b', 'c', 'd']]

new_lst = [[l[0:1]   [' '.join(l[1:-3])]   l[-3:]] if len(l) >= 6 else l for l in lst]
print(new_lst)

# Output
# [['a', 'b', 'c', 'd'], [['a', 'b c d', 'e', 'f', 'g']], ['a', 'b', 'c', 'd']]

join() takes a list as an argument instead of a string, and also try to refrain from using built in types like list as variable names.

  • Related