adjust all nested lists to the same length

  • Last Update :
  • Techknowledgy :

Ok, lets go through it line by line. Personally I don't think map is very idiomatic in Python so I would write this:

maxLen = max(map(len, myList))

As a generator expresion:

max_len = max(len(item) for item in my_list)

The best way to understand something in Python is just fire up the REPL and try it. So if you have my_list as a list of lists:

my_list = [
   [1],
   [1, 2],
   [1, 2, 3]
]

You may want to do a bit of premature optimization and call extend once instead of calling append several times because you think performance will be better this way (but you can't really tell it unless you have profiled both solutions):

for item in list:
   if len(item) < max_len:
   item.extend([None] * (max_len - len(item)))

Now what is going on here? In Python, list + list concatenates two copies of list, and list * 3 is the same as list + list + list. So in the first iteration of the for loop, item is [1], len(item) is 1 and max_len - len(item) is 3 - 1. Finally, [None] * 2 is [None, None] so after the call to extend the first item will be [1, None, None]. Same thing for the second item, its length is 2, 3 minus 2 is one and it will end up as [1, 2, None]. The 3rd item has the same length as max_len (3) so the if condition is false. The result will be:

[
   [1, None, None],
   [1, 2, None],
   [1, 2, 3]
]
for row in myList:

Suggestion : 2

The function len returns the length of a list, which is equal to the number of its elements. It is a good idea to use this value as the upper bound of a loop instead of a constant. That way, if the size of the list changes, you won’t have to go through the program changing all the loops; they will work correctly for any size list:,Since lists are mutable, it is often desirable to traverse a list, modifying each of its elements. The following squares all the numbers from 1 to 5:,Since pestilence is a member of the horsemen list, the in operator returns True. Since debauchery is not in the list, in returns False.,Each time through the loop, the variable i is used as an index into the list, printing the i-eth element. This pattern of computation is called a list traversal.

[10, 20, 30, 40]
["spam", "bungee", "swallow"]
["hello", 2.0, 5, [10, 20]]
>>>
if []:
...print 'This is true.'
   ...
   else:
      ...print 'This is false.'
      ...
      This is false. >>>
>>> vocabulary = ["ameliorate", "castigate", "defenestrate"] >>>
   numbers = [17, 123] >>>
   empty = [] >>>
   print vocabulary, numbers, empty['ameliorate', 'castigate', 'defenestrate'][17, 123][]
>>> print numbers[0]
17
>>> numbers[9-8]
123
>>> numbers[1.0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      TypeError: list indices must be integers

Suggestion : 3

1 week ago A nested ArrayList is a list within a list. Due to the dynamic nature of ArrayLists, we can have multiple dimensions of the list added on as per our requirement. Individual elements of such a list are lists themselves. Remember to import the java.util.Collections as it is part of the Collections framework. We create a nested ArrayList in the ... , 5 days ago Sep 04, 2021  · Every list has 10 numbers; Initial nested list size is 10; Every step increases the nested list size by 10 times more; Figure 4: Time complexity while we increase the list's dimensions. Let's isolate the non-numpy methods for a moment and examine the results. As we can see, while we increase the dimensions of the list, the _sum function becomes ... , 6 days ago Mar 02, 2019  · here the max_length=4 (the first column), the batch_size=3, and the sequence_length=[4, 3, 3] for the three users. All elements are lists with different lengths, representing different items a use choose once. , Instead of logging the sum, you could divide the sum by the length of the array before you return a final value. The way to do this is by taking advantage of the other arguments in the reduce method. The first of those arguments is the index. Much like a for-loop, the index refers to the number of times the reducer has looped over the array.


  mylist = list(list(data.frame(a = 3, b = 2, c = 4), data.frame(d = 5, e = 6, h = 8), data.frame(k = 2, e = 3, b = 5, m = 5)), list(data.frame(a = 32, b = 22, c = 42), data.frame(d = 5, e = 63, h = 82), data.frame(k = 2, e = 33, b = 5, m = 5)), list(data.frame(a = 33, b = 21, k = 41, c = 41), data.frame(d = 5, e = 61, h = 80), data.frame(k = 22, e = 3, b = 5, m = 5)))

.mapply(cbind, mylist, NULL) #[[1]] # a b c a b c a b k c #1 3 2 4 32 22 42 33 21 41 41 # #[[2]] # d e h d e h d e h #1 5 6 8 5 63 82 5 61 80 # #[[3]] # k e b m k e b m k e b m #1 2 3 5 5 2 33 5 5 22 3 5 5 

Suggestion : 4

To find the shape (or dimensions) of a nested list or tuple in Python, iterate over each element in the list or tuple and identify its length with the built-in len() function. This can become very complicated if the list or tuple has more than two dimensions. An example of how to identify the number of dimensions in a Python list or tuple, and the maximum size of each dimension is included below.,Finding the shape of a nested list or tuple is much more complicated than finding the shape of a single element because each element in a list of lists or tuple of tuples can have a different dimension. Unlike NumPy arrays, lists and tuples aren’t required to have a set number of rows or columns.,Now we need a way to update dims when a new dimension is found, or a new maximum value for the length of an existing dimension is observed. To do this we’ll write a function that takes dims as an input, alters it (or not) according to other arguments, and then returns the updated dimension list.,It’s possible that there’s a more elegant way to do this. Still, I think this example does a good job of illustrating the complexities of Python list and tuple shapes.

1._
list1 = [
   [1, 2, 3],
   [1, 2],
   [
      [2, 3, 4],
      [1, 3], 1
   ], 9, [1, 2, 3]
]

The trick with a list is that there’s no way to tell how many dimensions the list has without iterating through all the elements. That’s what we’re going to do here. As we iterate through the list we want to keep track of how many dimensions there are and the maximum size, or length, of each dimension. Let’s create a dims variable, and empty list, to keep track of the maximum length of each dimension. At then end of our script the length of dims will tell us the number of dimensions and the values in dims will tell us the maximum size of each dimension. It will be similar to a NumPy shape tuple, but for lists and tuples.

dims = []
3._
def set_dimension(dims, index, value):
   if len(dims) > index:
   if dims[index] < value:
   dims[index] = value
else:
   dims.append(value)
return dims

To check your work print dims. Your output should match the output below.

Output: [5]

There are 5 elements in list1. However, we cannot know what those elements are without iterating through each one. That’s what we’ll do now. Iterate through all the list elements with a nested loop. Within each loop check to see if an element is a list. If it is, use set_dimension to add a new dimension if it hasn’t been updated already or to update the size of the dimension. As stated, the example list only contains three dimensions. I’ve added a print statement in the third loop to indicate if a fourth dimension exists in the list so you can extend the functionality for other applications.

for i in range(len(list1)):
   if isinstance(list1[i], list):
   dims = set_dimension(dims, 1, len(list1[i]))
for j in range(len(list1[i])):
   if isinstance(list1[i][j], list):
   dims = set_dimension(dims, 2, len(list1[i][j]))
for k in range(len(list1[i][j])):
   if isinstance(list1[i][j][k], list):
   dims = set_dimension(dims, 3, len(list1[i][j][k]))
print('four dimensions')

Suggestion : 5

I have three sub-lists of unequal length. How could I remove, say the first element in the first list?? I have tried Drop without success. Better yet, how would I create the three lists of equal length in the first place???,and that gives some functions that can be looked up in the help system.,I peeked at one of the three using,At this point I'm guessing to go back to the source of this data or the source of the processing and ask for an explanation.

port = {
   "^GSPC",
   "GLD",
   "VCSH"
};
ret1 = QuantityMagnitude[
   FinancialData[#, "Return", {
      2021
   }]["Values"]] & /@ port;
In[120]: = Length[#] & /@ {ret1[[1]], ret1[[2]], ret1[[3]]}

Out[120] = {
   169,
   168,
   168
}

Perhaps

lists = {
   {
      1,
      2,
      3
   },
   {
      4,
      5,
      6,
      7
   },
   {
      8,
      9
   }
};
minlen = Min @ @Map[Length, lists];
res = Map[Take[#, minlen] & , lists]

which returns

{
   {
      1,
      2
   }, {
      4,
      5
   }, {
      8,
      9
   }
}

I peeked at one of the three using

port = {
   "^GSPC",
   "GLD",
   "VCSH"
};
ret1 = FinancialData[#, "Return", {
   2021
}] & /@ port;
FullForm[ret1[[1]]]

Suggestion : 6

You can change the value of a specific item in a nested list by referring to its index number.,When you want to insert an item at a specific position in a nested list, use insert() method.,You can use the built-in len() function to find how many items a nested sublist has.,You can access individual items in a nested list using multiple indexes.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[2])
# Prints['cc', 'dd', ['eee', 'fff']]

print(L[2][2])
# Prints['eee', 'fff']

print(L[2][2][0])
# Prints eee
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[-3])
# Prints['cc', 'dd', ['eee', 'fff']]

print(L[-3][-1])
# Prints['eee', 'fff']

print(L[-3][-1][-2])
# Prints eee
L = ['a', ['bb', 'cc'], 'd']
L[1][1] = 0
print(L)
# Prints['a', ['bb', 0], 'd']
L = ['a', ['bb', 'cc'], 'd']
L[1].append('xx')
print(L)
# Prints['a', ['bb', 'cc', 'xx'], 'd']
L = ['a', ['bb', 'cc'], 'd']
L[1].insert(0, 'xx')
print(L)
# Prints['a', ['xx', 'bb', 'cc'], 'd']