Reputation: 45
I would like to join word from one nested list together with the word "and" in between. For example:
l1 = [Patrick, Peter, Jerome], [Lisa, Karen, Alice]
l2 should be: [Patrick and Lisa, Peter and Karen, Jerome and Alice]
The code should not make a difference whether there are 2,3 or whatever amount of lists in the nested list.
I have tried iterating over the range of lists in the variable and then append the result to a new variable. However, the outcome is just the first combination or the results end after the second combination.
def names(one):
newlist = []
x = 0
for y in range(len(one)):
newlist.append(one[x][y] + " and " + one[x+1][y])
x += 1
return newlist
['Patrick and Lisa']
is what i got untill now. I know it has something to do with the iteration but since i am pretty new to python i got stuck.
Upvotes: 1
Views: 629
Reputation: 69755
It seems that l1
is a tuple of two elements. Use the following:
l2 = []
for name_a, name_b in zip(l1[0], l1[1]):
l2.append(name_a + ' and ' + name_b)
If you are using Python 3.6+ you can use an f-string:
l2 = []
for name_a, name_b in zip(l1[0], l1[1]):
l2.append(f'{name_a} and {name_b}')
Also keep in mind that you can also use a list-comprehension.
Python 3.6+
l2 = [f'{name_a} and {name_b}' for name_a, name_b in zip(l1[0], l1[1])]
l2 = [name_a + ' and ' + name_b for name_a, name_b in zip(l1[0], l1[1])]
Note: If you are not allowed to use zip
use range
and use index notation as follows:
l2 = []
for i in range(len(l1[0])):
name_a = l1[0][i]
name_b = l1[1][i]
l2.append(name_a + ' and ' + name_b)
Update: based on the previous comments, you should use the following:
l2 = []
for i in range(len(l1[0])):
l2.append(' and '.join(e[i] for e in l1))
Upvotes: 2
Reputation: 16908
You can use zip
to get a combination of names from sub lists and the list having "and" repeated the number of times elements are present in the first list one[0]
:
one = [['Patrick', 'Peter', 'Jerome'], ['Lisa', 'Karen', 'Alice']]
name_tup = zip(one[0], ["and"] * len(one[0]), one[1])
Then use a list comprehension to generate the out list from the tuple returned by zip
. Using unpacking the three elements are joined by a whitespace in between using the join
function:
list = [ " ".join([x, y, z]) for x, y, z in name_tup]
>>> list
['Patrick and Lisa', 'Peter and Karen', 'Jerome and Alice']
Upvotes: 1