So I wrote this code to get every single row in a grid
def rows(test):
r = []
for x in test:
r.append(x)
return str(r)
the grid is this btw
test = [["r","a","w","b","i","t"],
["x","a","y","z","c","h"],
["p","q","b","e","i","e"],
["t","r","s","b","o","g"],
["u","w","x","v","i","t"],
["n","m","r","w","o","t"]]
and after running rows(test)
, I get this
[['r', 'a', 'w', 'b', 'i', 't'], ['x', 'a', 'y', 'z', 'c', 'h'], ['p', 'q', 'b', 'e', 'i', 'e'], ['t', 'r', 's', 'b', 'o', 'g'], ['u', 'w', 'x', 'v', 'i', 't'], ['n', 'm', 'r', 'w', 'o', 't']]
but I want it to be
[['rawbit','xayzch','pqbeie','trsbog', 'uwxvit', 'nmrwot']
What should I change??
CodePudding user response:
Use .join
:
def rows(test):
r = list()
for row in test:
r.append("".join(row))
return r
>>> rows(test)
['rawbit', 'xayzch', 'pqbeie', 'trsbog', 'uwxvit', 'nmrwot']
CodePudding user response:
You can use ''.join()
like below:
>>> lst = [['r', 'a', 'w', 'b', 'i', 't'], ['x', 'a', 'y', 'z', 'c', 'h'], ['p', 'q', 'b', 'e', 'i', 'e'], ['t', 'r', 's', 'b', 'o', 'g'], ['u', 'w', 'x', 'v', 'i', 't'], ['n', 'm', 'r', 'w', 'o', 't']]
>>> list(map("".join, lst))
#OR
>>> [''.join(l) for l in lst]
['rawbit', 'xayzch', 'pqbeie', 'trsbog', 'uwxvit', 'nmrwot']
If you want as function
:
def rows(test):
# return [''.join(t) for t in test]
# Or
return list(map(''.join, test))