How to combine words from lists into one? - python

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
How to combine these two lists into one, and the output should be
['ad', 'be', 'cf']

You should use zip in conjunction with a list comprehension as follows:
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = [a+b for a, b in zip(list1, list2)]
print(list3)
Output:
['ad', 'be', 'cf']

The following code will work:
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = []
for i in range(len(list1)):
list3.append(list1[i] + list2[i])
print(list3)
Output:
['ad', 'be', 'cf']
Explanation:
We will first create a new list, list3 that will store the combination of list1 and list2. To combine the two lists, we will use a for loop to iterate through every index of both list1 and list2 and then use the .append() function to add the i'th element of list1 and list2 to list3.
I hope this helped! Please let me know if you have any further questions or clarifications :)

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
for i in range(len(list1)):
list1[i]+=list2[i]
print(list1)
#['ad', 'be', 'cf']

you can you zip to iterate over several iterables in parallel, producing tuples with an item from each one and then concatinate them using ''.join(sequence).
In [2]: ["".join(i) for i in zip(list1, list2)]
Out[2]: ['ad', 'be', 'cf']

Related

Joint nested list in Python

How to convert a nested list like below?
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
-> [['a','b','c'], ['d','e','f']]
I found a similar question. But it's a little different.
join list of lists in python [duplicate]
Update
Mine is not smart
new = []
for elm in d:
tmp = []
for e in elm:
for ee in e:
tmp.append(ee)
new.append(tmp)
print(new)
[['a', 'b', 'c'], ['d', 'e', 'f']]
Lots of ways to do this, but one way is with chain
from itertools import chain
[list(chain(*x)) for x in d]
results in:
[['a', 'b', 'c'], ['d', 'e', 'f']]
sum(ls, []) to flatten a list has issues, but for short lists its just too concise to not mention
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
[sum(ls, []) for ls in d]
Out[14]: [['a', 'b', 'c'], ['d', 'e', 'f']]
This is a simple solution for your question
new_d = []
for inner in d:
new_d.append([item for x in inner for item in x])

Sorting a 2D list alphabetically?

I have a 2D list such as this:
lst = [['c', 'd', 'b'], ['d', 'c', 'a'], ['b', 'a', 'c']]
I would first like to sort each list within the list alphabetically like this:
lst = [['b', 'c', 'd'], ['a', 'c', 'd'], ['a', 'b', 'c']]
And finally, I would like to sort the whole list alphabetically which takes into account each element in a sublist:
lst = [['a', 'b', 'c'], ['a', 'c', 'd'], ['b', 'c', 'd']]
What would be the fastest way to achieve this? Thank you.
The fastest way in general should be just as you described it:
for sublist in lst:
sublist.sort()
lst.sort()
Alternatively, if you want to do it out of place:
new_lst = [sorted(sublist) for sublist in lst]
new_lst.sort()

delete items from list of list: pythonic way

I've this kind of list of list (only two nested level):
my_list = [['A'], ['B'], ['C','D','A','B'], ['E'], ['B', 'F', 'G'], ['H']]
I've a list of items to delete in my_list:
to_del = ['A','B']
this is my idea of code to delete to_del elements from my_list:
for i in my_list:
for d in to_del:
if d in i:
i.remove(d)
Output:
[[], [], ['C', 'D'], ['E'], ['F', 'G'], ['H']]
Here my questions:
Can you suggest a more pythonic/elegant way to do the same
Can you suggest a smart way to generalize the number of nested levels
e.g my_list = [ ['A'], ['B'], ['C', ['D', 'E', ['F']], 'G'], ['H'] ]
The ideal method will have a boolean argument empty_lists to decide whether or not keep empty lists.
Try list comprehension:
my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
Output:
>>> my_list
[[], [], ['C', 'D'], ['E'], ['F', 'G'], ['H']]
With nested list comprehensions:
[[y for y in x if y not in to_del] for x in my_list]
With list comprehension and lambda filter:
[filter(lambda y: y not in to_del, x) for x in my_list]
An attempt for the general case of arbitrarily nested lists:
def f(e):
if not isinstance(e,list):
if e not in to_del:
return e
else:
return filter(None,[f(y) for y in e])
to_del = ['A','B']
my_list= [['A'], ['B',['A','Z', ['C','Z','A']]], ['C','D','A','B'],['E'], ['B','F','G'], ['H']]
>>> f(my_list)
[[['Z', ['C', 'Z']]], ['C', 'D'], ['E'], ['F', 'G'], ['H']]

Permutations of the elements of two lists with order restrictions

I would like to merge two input lists together and get all permutations of their elements such that the ordering of the elements in each input list is retained.
For example, if I have two lists: ['b','a'] and ['c','d'], I would like to get the following lists:
['b', 'a', 'c', 'd'],
['b', 'c', 'a', 'd'],
['b', 'c', 'd', 'a'],
['c', 'b', 'a', 'd'],
['c', 'b', 'd', 'a'],
['c', 'd', 'b', 'a']
where the order of the elements from the original lists is retained (b comes before a, c comes before d).
I have found a post dealing with a similar problem but using strings as inputs instead of lists: Restricted Permutations of Strings in Python. For example, with the strings "ba" and "cd" as inputs, strings "bacd", "bcad", "bcda", "cbad", "cbda", "cdba" will be returned.
I have tried to adapt the code there to my problem, but it didn't work. Using the same example as above, I got [None, None, None, None, None, None] instead of the 6 lists that I expected. Below is the code I used.
def ordered_permutations(list1, list2):
perms = []
if len(list1) + len(list2) == 1:
return [list1 or list2]
if list1:
for item in ordered_permutations(list1[1:], list2):
perms.append([list1[0]].append(item))
if list2:
for item in ordered_permutations(list1, list2[1:]):
perms.append([list2[0]].append(item))
return perms
list.append() returns None as the list is altered in-place. You should use concatenation instead:
def ordered_permutations(list1, list2):
perms = []
if len(list1) + len(list2) == 1:
return [list1 or list2]
if list1:
for item in ordered_permutations(list1[1:], list2):
perms.append([list1[0]] + item)
if list2:
for item in ordered_permutations(list1, list2[1:]):
perms.append([list2[0]] + item)
return perms
This then produces your required output:
>>> def ordered_permutations(list1, list2):
... perms = []
... if len(list1) + len(list2) == 1:
... return [list1 or list2]
... if list1:
... for item in ordered_permutations(list1[1:], list2):
... perms.append([list1[0]] + item)
... if list2:
... for item in ordered_permutations(list1, list2[1:]):
... perms.append([list2[0]] + item)
... return perms
...
>>> for combo in ordered_permutations(['b','a'], ['c', 'd']):
... print combo
...
['b', 'a', 'c', 'd']
['b', 'c', 'a', 'd']
['b', 'c', 'd', 'a']
['c', 'b', 'a', 'd']
['c', 'b', 'd', 'a']
['c', 'd', 'b', 'a']

How to use *args to combine multiple lists?

I currently have this function, which I'd like to make scalable to take in more lists. In other words, I'd like to use this function whether I have to combine 2 lists or 10 lists.
l1 = [['a','b','c'],['d','e','f']]
l2 = [['A','B','C'],['D','E','F']]
[L1 + L2 for L1, L2 in zip(l1, l2)]
result should be:
[['a','b','c','A','B','C'],['d','e','f','D','E','F']]
Use:
[sum(l, []) for l in zip(*lists)]
Demo:
>>> l1 = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> l2 = [['A', 'B', 'C'], ['D', 'E', 'F']]
>>> lists = (l1, l2)
>>> [sum(l, []) for l in zip(*lists)]
[['a', 'b', 'c', 'A', 'B', 'C'], ['d', 'e', 'f', 'D', 'E', 'F']]
or, as a function:
def combine_lists(*lists):
return [sum(l, []) for l in zip(*lists)]
combine_lists(l1, l2)

Categories

Resources