List comprehensions - python

I have a for loop for outputting values into a list.
This is my output:
[[23, 34, 34] [34,21,34,56] [21,3,5,67]]
Below is my code that works for the above output:
y_train = ([[word2index[w] for w in sent[1:]] for sent in tokenized_sentences]).
But I would like to append a value at the end of each smaller list. How can I modify my code to handle this? My desired output should look like this:
[[23,34,34,**2**][34,21,34,56,**2**][21,3,5,67,**2**]]
so I would like to append a new value at the end of each inner list.
P.S. A normal for loop handling this would be good too.

for x in y_train:
x.append(element)
example:
>>> listOfLists = [[1,2], [2,3], [4,5]]
>>> for x in listOfLists:
... x.append(2)
>>> listOfLists
[[1, 2, 2], [2, 3, 2], [4, 5, 2]]

Related

Nested list - create new nested list with indices as items

I would like to create a new nested list from an already existing nested list. This new list should include the indices+1 from the existing list.
Example:
my_list = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
Result:
my_new_list = [[1,2,3],[1,2],[1],[1,2,3,4]]
How can I create such a list?
save a python loop, force iteration of range (required for python 3) in a list comprehension, so it's faster than a classical double nested comprehension:
my_list = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
index_list = [list(range(1,len(x)+1)) for x in my_list]
There's a few ways to do this, but the first that comes to mind is to enumerate the elements with a starting index of 1 in a nested list comprehension.
>>> [[index for index, value in enumerate(sub, 1)] for sub in my_list]
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Another solution could be:
new_list = [list(range(1,len(item)+1)) for item in my_list]
Here is are some simple solutions:
>>> lst = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
>>> out = [[x+1 for x,_ in enumerate(y)] for y in lst]
>>> out
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
>>>
>>>
>>> out = [[x+1 for x in range(len(y))] for y in lst]
>>> out
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Using nested list comprehension
First you want a list with every number from 1 to the length of your sublist. There are several ways to do this with list comprehension.
For example
[i for i in range(1, len(sublist) + 1)]
or
[i + 1 for i in range(len(sublist))]
Second you want to do this for every sublist inside your my_list. Therefore you have to use nested list comprehension:
>>> my_list = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
>>> my_new_list = [[i+1 for i in range(len(sublist))] for sublist in my_list]
>>> my_new_list
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Using list comprehension with range
Another way would be using the range built-in function as a generator for your sublists:
>>> [list(range(1, len(sublist) + 1)) for sublist in my_list]
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Using map with range
Or you can use the map built-in function
>>> list(map(
... lambda sublist: list(range(1, len(sublist) + 1)),
... my_list
... ))
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]

Python converting array values to separate array

I have a python array that looks like this: [1, 2, 3, 4, 5]
I want it to look like this: [[1], [2], [3], [4], [5]]
How do I go about doing this?
Thanks!
I assume you are talking about lists. This should work:
l = [1, 2, 3, 4, 5]
out = [[i] for i in l]
You can also do it like this using append method of list
list_a = [1,2,3,4,5]
new_list = []
for i in list_a:
new_list.append([i])

integer extraction from list of lists in python

I have a list that contain lists:
mylist=[[2],[9],[3],[5],[7]]
Is there a way in python to get the value of the inner list (not just print it)?
Therefore, we would get integer 2 from the list mylist[0]. Without iterating the whole mylist.
If you want to get a specific value, use mylist[instance][0].
This would work, because it gets the ith value, but then gets the 0th value of that because it is still a list:
>>> mylist=[[2],[9],[3],[5],[7]]
>>> mylist[0]
[2]
>>> mylist[0][0]
2
>>>
Alternatively, you could flatten it and then access it normally:
>>> mylist=[[2],[9],[3],[5],[7]]
>>> mylist = [item for sub in mylist for item in sub]
>>> mylist
[2, 9, 3, 5, 7]
>>> mylist[0]
2
>>>
A list of lists is similar to having a 2-D array. To reference an element of the inner list, just use
mylist[i][j]
where i refers to the index of the list and j to the element in that list.
In the case of 2, this would be:
mylist[0][0]
Think of your list like this:
mylist=
[[2],
[9],
[3],
[5],
[7]]
mylist[0] = [2] which is an array, to access the number in the array mylist as explained is mylist[0][0] which = the int 2
eg
mylist[1][0] = 2
If mylist was
mylist=
[[2, 3],
[9, 10],
[3, 4],
[5, 6],
[7, 8]]
mylist[0][1] = 3 and mylist[1][1] = 10
mylist=[[2],[9],[3],[5],[7]]
newList=[]
for each in str(mylist).replace('[','').replace(']','').strip().split(','):
newList.append(int(each))
print newList
or
newList = eval('[' + str(mylist).replace('[','').replace(']','').strip() +']')

Adding elements to List using a comprehension

Lets say I have a list:
List = [1,2,3,4,5]
I want to use a comprehension to output a list of lists for every element, let's say i, in "List" containing 1,2,...,i. So the comprehension would output:
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
The same would work for a List of List = [1,3,5] where the output would be:
[[1],[1,2,3],[1,2,3,4,5]
I do not want to use any modules like numpy or itertools
Any help would me much appreciated!
Sure:
>>> [range(1, i+1) for i in List]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

Processing a list of lists

I have a list of lists, say:
arr = [[1, 2], [1, 3], [1, 4]]
I would like to append 100 to each of the inner lists. Output for the above example would be:
arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
I can of course do:
for elem in arr:
elem.append(100)
But is there something more pythonic that can be done? Why does the following not work:
arr = [elem.append(100) for elem in arr]
The second version should be written like arr = [elem + [100] for elem in arr]. But the most pythonic way if you ask me is the first one. The for construct has it's own use, and it suits very well here.
Note that your code also works - the only thing you have to know is that there is no need to assign result to variable in such a case:
arr = [[1, 2], [1, 3], [1, 4]]
[x.append(100) for x in arr]
After execution arr will contain updated list [[1, 2, 100], [1, 3, 100], [1, 4, 100]], e.g it work like in-place update, but this not very common practice to do this.
The same result you will get in the next case:
map(lambda x: x.append(100), arr)
As was discussed you can use list comprehension or map to do this with assigning result to any variable:
res = map(lambda x: x + [100], arr)
You can do
[a + [100] for a in arr]
The reason why your append doesn't work is that append doesn't return the list, but rather None.
Of course, this is more resource intensive than just doing append - you end up making copies of everything.
This is the more pythonic way
for elem in arr:
elem.append(100)
but as an option you can also try this:
[arr[i].append(100) for i in range(len(arr))]
print arr # It will return [[1, 2, 100], [1, 3, 100], [1, 4, 100]]

Categories

Resources