List of Lists of Lists of... to one List - python-3.x

How can I convert List of Lists of Lists into one List? For example I would like to make one list which contains all elements from all nested lists, i.e if I have:
l = [[["A", ["B"]], ["C", "D"]], [["E", "F"], ["A"]]]
then the results should be:
["A", "B", "C", "D", "E", "F", "A"]

This is perhaps not the most efficient, or most pythonic way:
def extract(a):
#recursive algorithm for extracting items from a list of lists and items
if type(a) is list:
l = []
for item in a:
l+=extract(item)
return l
else:
return [a]
Essentially what this does is check if the input is a list. If it is, we split it up into its elements, and run the function on those elements. When we get to a non-list, we return those, forming a complete list.
Another way of doing this would be using a global list to store each element. Again, this isn't the most efficient or pythonic way:
l = []
def extract(a):
#recursive algorithm for extracting items from a list of lists and items
if type(a) is list:
for item in a:
extract(item)
else:
global l
l.append(a)

Related

Iterate through a list of tuple

i have a list of tuples:
tuple_list = [('remarkably','remark'),('prevented','prevent'),...]
I am trying to create a dictionary where the key is the stemmer and the value is the list of words with that stemmer.
How do I go about doing this?
this is what I have so far and it doesn't seem to be working:
stem_dict = {}
for index, tuple in tuple_list:
if tuple == same_words:
stem_dict += tuple
i am looking for an output similar to this:
output:{‘achiev’: [‘achieved’, ‘achieve’]
‘accident’: [‘accidentally’, ‘accidental’] … }

How flatten a nested list of strings using two list compehension

I have the next list with strings and a nested list inside. And I want to use two list comprehension to flat it:
I am trying to use two nested list comprehension :
tweet_list=['!iniciamos', 'la', ['mi', 'banco', 'banco', 'señal'], 'con', 'nuestro', 'invitado', 'especial']
flat=[]
flated_list= [[flat.append(sub_elem) for sub_elem in elem] if isinstance(elem,list) else flat.append(elem) for elem in tweet_list]
I am getting two nest lists of Nones. How could I fix it?
out = [vv for v in tweet_list for vv in ([v] if isinstance(v, str) else v)]
print(out)
Prints:
['!iniciamos', 'la', 'mi', 'banco', 'banco', 'señal', 'con', 'nuestro', 'invitado', 'especial']

How to subtract adjacent items in list with unknown length (python)?

Provided with a list of lists. Here's an example myList =[[70,83,90],[19,25,30]], return a list of lists which contains the difference between the elements. An example of the result would be[[13,7],[6,5]]. The absolute value of (70-83), (83-90), (19-25), and (25-30) is what is returned. I'm not sure how to iterate through the list to subtract adjacent elements without already knowing the length of the list. So far I have just separated the list of lists into two separate lists.
list_one = myList[0]
list_two = myList[1]
Please let me know what you would recommend, thank you!
A custom generator can return two adjacent items at a time from a sequence without knowing the length:
def two(sequence):
i = iter(sequence)
a = next(i)
for b in i:
yield a,b
a = b
original = [[70,83,90],[19,25,30]]
result = [[abs(a-b) for a,b in two(sequence)]
for sequence in original]
print(result)
[[13, 7], [6, 5]]
Well, for each list, you can simply get its number of elements like this:
res = []
for my_list in list_of_lists:
res.append([])
for i in range(len(my_list) - 1):
# Do some stuff
You can then add the results you want to res[-1].

Matching character lists of unequal length

I want to match two lists from which one list is smaller while other is a bigger one. If a match occurs between two lists then put the matching element in a new list at the same index instead of putting it another index. You can understand my question from the code given below:
list1=['AF','KN','JN','NJ']
list2=['KNJ','NJK','JNJ','INS','AFG']
matchlist = []
smaller_list_len = min(len(list1),len(list2))
for ind in range(smaller_list_len):
elem2 = list1[ind]
elem1 = list2[ind][0:2]
if elem1 in list2:
matchlist.append(list1[ind])
Obtained output
>>> matchlist
['KNJ', 'NJK', 'JNJ']
Desired Output
>>> matchlist
['AFG', 'KNJ', 'JNJ', 'NJK']
Is there a way to get the desired output?
Use a nested loop iterating over the 3-char list. When an item in that list contains the current item in the 2-char list, append it and break out of the inner loop:
list1=['AF','KN','JN','NJ']
list2=['KNJ','NJK','JNJ','INS','AFG']
matchlist = []
smaller_list_len = min(len(list1),len(list2))
for ind in range(smaller_list_len):
for item in list2:
if list1[ind] in item:
matchlist.append(item)
break
Given the question doesn't specify any constraints, in a more pythonic way, using a list comprehension:
list1=['AF','KN','JN','NJ']
list2=['KNJ','NJK','JNJ','INS','AFG']
matchlist=[e2 for e1 in list1 for e2 in list2 if e2.startswith(e1)]
produces
['AFG', 'KNJ', 'JNJ', 'NJK']

How to use re.compile within a for loop to extract substring indices

I have a list of data from which I need to extract the indices of some strings within that list:
str=['cat','monkey']
list=['a cat','a dog','a cow','a lot of monkeys']
I've been using re.compile to match (even partial match) individual elements of the str list to the list:
regex=re.compile(".*(monkey).*")
b=[m.group(0) for l in list for m in [regex.search(l)] if m]
>>> list.index(b[0])
3
However, when I try to iterate over the str list to find the indices of those elements, I obtain empty lists:
>>> for i in str:
... regex=re.compile(".*(i).*")
... b=[m.group(0) for l in list for m in [regex.search(l)] if m]
... print(b)
...
[]
[]
I imagine that the problem is with regex=re.compile(".*(i).*"), but I don't know how to pass the ith element as a string.
Any suggestion is very welcome, thanks!!
It looks like you need to use string formatting.
for i in str:
match_pattern = ".*({}).*".format(i)
regex = re.compile(match_pattern)
b = [m.group(0) for l in list for m in [regex.search(l)] if m]
print(b)

Resources