list1 = [['apple','b','c'] ,['dolly','e','f']]
list2 =[['awsme','b','c'] ,['dad','e','f'],['tally','e','f']]
list_combine = [item for sublst in zip(list1, list2) for item in sublst]
print(list_combine)
Expected Output:
list_combine = [['apple','b','c'] ,['dolly','e','f'],['awsme','b','c'] ,['dad','e','f'],['tally','e','f']]
How to merge 2 unequal nested list into single nested list in python
You can just use the '+' operator to join 2 lists.
list_combine = list1 + list2
print(list_combine)
Output
list_combine = [['apple','b','c'] ,['dolly','e','f'],['awsme','b','c'] ,['dad','e','f'],['tally','e','f']]
You may simply concatenate the two lists by defining a new variable like list3 or whatever you call.
Also due to PEP8, I just modified your code in a more Pythonic way so that it would be more readable. Things like space before comma in not suggested, but after that is recommended. This recommendation is not just in Python, but also it is the better way to write in English grammatically too.
You may check this out and inform me should you have any doubts and questions regarding my answer:
list1 = [['apple', 'b', 'c'], ['dolly', 'e', 'f']]
list2 = [['awsme', 'b', 'c'], ['dad', 'e', 'f'], ['tally', 'e', 'f']]
list3 = list1 + list2
print(list3)
I hope it would be useful.
Related
This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 1 year ago.
I have the following list:
my_list=[[['A','B'],'C'],[['S','A'],'Q']]
How I can remove the bracket from the first two elements?
output:
my_list=[['A','B','C'],['S','A','Q']]
Slice it in?
for a in my_list:
a[:1] = a[0]
This produces the desired output:
[x[0]+[x[1]] for x in my_list]
my_list=[
[['A','B'],'C'],
[['S','A'],'Q'],
]
result = [[item1, item2, item3] for (item1, item2), item3 in my_list]
>>> result
[['A', 'B', 'C'], ['S', 'A', 'Q']]
You can use the flattening solution in Cristian's answer on Flatten an irregular list of lists.
>>> [list(flatten(x)) for x in my_list]
[['A', 'B', 'C'], ['S', 'A', 'Q']]
Other people have already given the oneline solutions, but let's take a step back and think about how to approach this problem, so you can solve it for yourself.
The tools you need:
for [element] in list: Iterate over each element in a list
list[i]: Get the ith element of a list
list.append(element): Add an element to a list
Let's start with the simple case. We have [['A','B'],'C'] and want ['A','B','C'].
We want to
Get the sublist ['A', 'B']
Get the single item that isn't in the sublist, 'C'
Add the single item into the sublist
Make the sublist the main list
Sometimes it's easiest to sketch these things out in the python shell:
>>> l = [['A','B'],'C']
>>> l[0]
['A', 'B']
>>> l[1]
'C'
>>> l[0].append(l[1])
>>> l = l[0]
>>> l
['A', 'B', 'C']
Now, we can build up a function to do this
def fix_single_element(element):
"""
Given a list in the format [['A','B'],'C']
returns a list in the format ['A','B','C']
"""
# We use copy since we don't want to mess up the old list
internal_list = element[0].copy()
last_value = element[1]
internal_list.append(last_value)
return internal_list
Now we can use that:
>>> for sublist in my_list:
... print(sublist)
...
[['A', 'B'], 'C']
[['S', 'A'], 'Q']
Note that the sublists are exactly the problem we just solved.
>>> new_list = []
>>> for sublist in my_list:
... new_list.append(fix_single_element(sublist))
...
>>> new_list
[['A', 'B', 'C'], ['S', 'A', 'Q']]
There are LOTS of ways to do any particular task, and this is probably not the "best" way, but it's a way that will work. Focus on writing code you understand and can change, not the shortest code, especially when you start.
I'm learning python and I have been trying to make an automatic list of lists. For example:
The next list, which I have to split to get a list of separated letters, and then join them again to make a two lists of separated letters
lists=[['a,b,c,h'],['d,e,f,g']]
print('list length', len(lists))
splited=[]
splited1=lists[0][0].split(',')
print(splited1) #['a', 'b', 'c', 'h']
splited2=lists[1][0].split(',')
print(splited2) #['d', 'e', 'f', 'g']
listcomb=[splited1,splited2]
print(listcomb) #[['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g']]
This is what I want to get, a list that have 2 lists, but in the case I have to get more lists inside that list i want to make it automatic with a for loop.
My try, but it didn't work
listcomb2=zip(splited1,splited2)
print(listcomb2)
sepcomb = list()
print(type(sepcomb))
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
print(sepcomb)
I'm having problems with splitting the letters and then joining them in a new list. Pls help
Make some tweak in your code. As we can see lenght of sepcomb is 0 so use append method to avoid this problem. As sepcomb[x]=[sep] is is assignment to x-index but it x index doesn't exist so, it will raise error
change:
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
to
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb.append(sep)
Method-2
sepcomb = list(i[0].split(',') for i in lists)
You can simply do the following:
final=[splinted1]+[splinted2]
Or a better way directly from the lists variable would be:
final=[value[0].split(',') for value in lists]
Here you go:
lists = [['a,b,c,h'],['d,e,f,g']]
listcomb = []
for each in lists:
splited = each[0].split(',')
listcomb.append(splited)
print(listcomb)
I am searching through a list like this:
my_list = [['a','b'],['b','c'],['a','x'],['f','r']]
and I want to see which elements come with 'a'. So first I have to find lists in which 'a' occurs. Then get access to the other element of the list. I do this by abs(pair.index('a')-1)
for pair in my_list:
if 'a' in pair:
print( pair[abs(pair.index('a')-1)] )
Is there any better pythonic way to do that?
Something like: pair.index(not 'a') maybe?
UPDATE:
Maybe it is good to point out that 'a' is not necessarily the first element.
in my case, ['a','a'] doesn't happen, but generally maybe it's good to choose a solution which handles this situation too
Are you looking for elements that accompany a? If so, a simple list comprehension will do:
In [110]: [x for x in my_list if 'a' in x]
Out[110]: [['a', 'b'], ['a', 'x']]
If you just want the elements and not the pairs, how about getting rid of a before printing:
In [112]: [(set(x) - {'a'}).pop() for x in my_list if 'a' in x]
Out[112]: ['b', 'x']
I use a set because a could either be the first or second element in the pair.
If I understand your question correctly, the following should work:
my_list = filter(
lambda e: 'a' not in e,
my_list
)
Note that in python 3, this returns a filter object instance. You may want to wrap the code in a list() command to get a list instance instead.
That technique works ok here, but it may be more efficient, and slightly more readable, to do it using sets. Here's one way to do that.
def paired_with(seq, ch):
chset = set(ch)
return [(set(pair) - chset).pop() for pair in seq if ch in pair]
my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r']]
print(paired_with(my_list, 'a'))
output
['b', 'x']
If you want to do lots of tests on the same list, it would be more efficient to build a list of sets.
def paired_with(seq, ch):
chset = set(ch)
return [(pair - chset).pop() for pair in seq if ch in pair]
my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r']]
my_sets = [set(u) for u in my_list]
print(my_sets)
print(paired_with(my_sets, 'a'))
output
[{'b', 'a'}, {'c', 'b'}, {'x', 'a'}, {'r', 'f'}]
['b', 'x']
This will fail if there's a pair like ['a', 'a'], but we can easily fix that:
def paired_with(seq, ch):
chset = set(ch)
return [(pair - chset or chset).pop() for pair in seq if ch in pair]
my_list = [['a','b'], ['b','c'], ['x','a'], ['f','r'], ['a', 'a']]
my_sets = [set(u) for u in my_list]
print(paired_with(my_sets, 'a'))
output
['b', 'x', 'a']
Dear Reader of this post,
do you have an idea how to form the sequence of a union of two lists efficiently in Python? Suppose there are the two following lists:
list_a = [['a','b'],['a','c'],['b','c']]
list_b = ['h','i']
and I want to calculate:
new_list = [['a','b','h'],['a','b','i'],['a','c','h'],['a','c','i'],['b','c','h'],
['b','c','i']].
Up to now, I am using the following loops:
new_list = [r+[j] for j in list_b for r in list_a]
However, I find this ugly. I do not like the two loops. I prefer using functions instead.
Do you have another idea to achieve the desired task? (Among other things, I tried to follow this Get the cartesian product of a series of lists in Python suggestion, but to no avail.)
I am grateful for any suggestions!
Best regards,
Fabian
You could use itertools.product:
[a+[b] for a, b in itertools.product(list_a, list_b)]
However, there's nothing really wrong with the way you did it. Using two loops in a list comprehension is fine if you really need to get every combination of elements from both iterables. The product solution, though, does have the advantage that it is more easily extended to more iterables (e.g., it's easy to get every combination of three or four or ten lists, whereas deeply nested loops can become cumbersome).
How does it look?
>>> new_list = []
>>> for item in itertools.product(list_a, list_b):
... new_list.append([x for li in list(item) for x in li])
...
>>> new_list
[['a', 'b', 'h'], ['a', 'b', 'i'], ['a', 'c', 'h'], ['a', 'c', 'i'], ['b', 'c', 'h'], ['b', 'c', 'i']]
>>>
lists = [[a,b,c,d],[a,b,c,d,e],[a,b,c,x],[a,b,c,d,e,f]....lots]
common_items = [a,b,c]
uncommon_items = [[d], [d,e], [x], [d,e,f]]
common_elements(lists[0],lists[1])
def common_elements(list1, list2):
return [element for element in list1 if element in list2]
lot of the answers on SO only able to do this with two lists at a time. need one that can handle any number of lists, and returns two lists.
Note: Order of list is important which leaves out sets.
Note: Must be lowest common items from each list, not based on the just the first list in lists.
The easiest way is to use sets, but you will lose ordering.
lists = [['a','b','c','d'],
['a','b','c','d','e'],
['a','b','c','x'],
['a','b','c','d','e','f']]
sets = map(set, lists)
common = set.intersection(*sets)
uncommon = [s-common for s in sets]
print common # set(['a', 'c', 'b'])
print uncommon # [set(['d']), set(['e', 'd']), set(['x']), set(['e', 'd', 'f'])]
Sets are the best way to represent common elements. You can maintain the order of uncommon elements by using a different lists comprehension.
uncommon = [[x for x in l if x not in common] for l in lists]
print uncommon # [['d'], ['d', 'e'], ['x'], ['d', 'e', 'f']]
Assuming the elements of common appear in the same order in all lists, you can then convert the common set to a list.
common = [x for x in lists[0] if x in common]
This solution preserves the order as well.
common, uncommon = lists[0], lists[0]
for clist in lists:
common = [item for item in common if item in clist]
uncommon = [[item for item in clist if item not in common] for clist in lists ]
print common, uncommon
Output
['a', 'b', 'c'] [['d'], ['d', 'e'], ['x'], ['d', 'e', 'f']]
Edit: As per OP's request in the comments
common = lists[0]
from itertools import takewhile
for l1, l2 in zip(lists, lists[1:]):
common = [i[0] for i in takewhile(lambda i: i[0] == i[1] == i[2], zip(l1, l2, common))]
uncommon = [clist[len(common):] for clist in lists]
print common, uncommon
Well I will do it this way...
Code:
def lcs(l,key=None):
if key==None: key=min(l,key=len)
t = [x for x in l if key in x]
return key if t == l else lcs(l,key[:-1])
if __name__=='__main__':
lists = [['a','b','c','d'],
['a','b','c','d','e'],
['a','b','c','x'],
['a','b','c','d','e','f']]
l = [''.join(item) for item in lists]
print lcs(l)
Output:
abc
Well I dont know much about complexity and such, but this code can solve the problem.
Hope this helps :)