-1

Suppose I am having a list (which is collection of list of lists), say the list is defined as follows as try_list:

  try_list = [['sun', 'Hello' 'star', 'cluster', 'douglas'], 
              ['age', 'estimate', 'scale', 'moon', 'hi'], 
              ['cosmos', 'mystery', 'system', 'graph']]

I want to add a special character _ or # to each word at the starting and ending point of the list.

For example, the try_list should look like this:

[['_sun_', '_Hello_', '_star_', '_cluster_', '_douglas_'],
 ['_age_', '_estimate_', '_scale_', '_moon_', '_hi_'],
 ['_cosmos_', '_mystery_', '_system_', '_graph_']]

What I have tried is working smoothly for a list, which is shown as follows.

try_list = ['sun', 'Hello' 'star', 'cluster', 'douglas', 'age',  'estimate', 'scale', 'moon', 'hi', 'cosmos', 'mystery', 'system', 'graph']
injected_tokens = []
temp = "_"
with open('try_try.txt', 'w', encoding='utf-8') as d2:
   for word in try_list:
       new_list.append(temp+word+temp)
   d2.write(injected_tokens)

The above code-snippet works perfectly fine for a list not list of lists?

How to achieve the same in list of lists?

Any idea is deeply appreciated!

Thanks!

yatu
  • 86,083
  • 12
  • 84
  • 139
M S
  • 894
  • 1
  • 13
  • 41

1 Answers1

5

You can use a list comprehension:

[[f'_{x}_' for x in i] for i in try_list]

[['_sun_', '_Hello_', '_star_', '_cluster_', '_douglas_'],
 ['_age_', '_estimate_', '_scale_', '_moon_', '_hi_'],
 ['_cosmos_', '_mystery_', '_system_', '_graph_']]

Or using map:

[list(map(lambda x: f'_{x}_', i)) for i in try_list]
yatu
  • 86,083
  • 12
  • 84
  • 139