2

I am trying to do following operation using list comprehensions:

Input: [['hello ', 'world '],['foo ',' bar']]
Output: [['hello', 'world'], ['foo', 'bar']]

Here is how one can do it without list comprehensions:

a = [['hello ', 'world '],['foo ',' bar']]
b = []

for i in a:
   temp = []
   for j in i:
      temp.append( j.strip() )
      b.append( temp )

print(b)
#[['hello', 'world'], ['foo', 'bar']]

How can I do it using list comprehensions?

Sait
  • 19,045
  • 18
  • 72
  • 99

4 Answers4

2
a = [['hello ', 'world '],['foo ',' bar']]
b = [[s.strip() for s in l] for l in a]
print(b)
# [['hello', 'world'], ['foo', 'bar']]
Mike
  • 19,114
  • 12
  • 59
  • 91
2

Simply next one list comprehension as each element of a larger list comprehension:

>>> i = [['hello ', 'world '],['foo ',' bar']]
>>> o = [[element.strip() for element in item] for item in i]
>>> o
[['hello', 'world'], ['foo', 'bar']]

Or use list() and map():

>>> i = [['hello ', 'world '],['foo ',' bar']]
>>> o = [list(map(str.strip, item)) for item in i]
>>> o
[['hello', 'world'], ['foo', 'bar']]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

something like this?

input = [['hello ', 'world '], ['foo ',' bar']]

output = [[item.strip() for item in pair] for pair in input]

print output


[['hello', 'world'], ['foo', 'bar']]
gary
  • 685
  • 6
  • 14
0
grid = [[1,1,0],[0,1,0],[1,0,1]]
visited_arr = [[False for elm in i ]for i in grid]
print(visited_arr)


[[False,False, False],[False,False, False],[False,False, False]]